Прежде всего, используйте map
для сопоставления массива с числом (элементов):
.map { $0?.count ?? 0 } // return 0 if array is nil
Чем используйте scan
, чтобы извлечь текущий и предыдущий элементы, например:
.scan((0, 0)) { previousPairOfValues, newValue in
return (previousPairOfValues.1, newValue) // create new pair from newValue and second item of previous pair
}
Затем используйте filter
, чтобы передать только растущие значения:
.filter { $0.1 > $0.0 } // newer value greater than older value
Затем сопоставьте его с последним значением:
.map { $0.1 }
Соедините все вместе:
behaviorRelay
.compactMap { $0?.items }
.map { $0?.count ?? 0 } // return 0 if array is nil
.scan((0, 0)) { previousPairOfValues, newValue in
return (previousPairOfValues.1, newValue) // create new pair from newValue and second item of previous pair
}
.filter { $0.1 > $0.0 } // newer value greater than older value
.map { $0.1 }
.subscribe(onNext: { elementCount in
print("items has one more element.")
print("there are \(elementCount) items now")
}).disposed(by: bag)