Objective
This article will learn RxSwift
about the math and set operators, which are included in the RxSwift
:
ToArray
Converts a Observable
sequence into an array and converts it to a new Observable
sequence launch, and then ends.
let disposeBag = DisposeBag() Observable.of(1,2,3,4,5).toArray().subscribe(onNext: {print($0)}).disposed(by: disposeBag)
Operation Result:
[1, 2, 3, 4, 5]
Reduce
Using an initial value and an operator, Observable
all elements in the sequence are accumulated and converted into a single event signal. (PS: And map
Some of the difference is: map
to operate on a single element, reduce
for all elements accumulated operations)
let disposeBag = DisposeBag() Observable.of(1,10,100).reduce(1, accumulator: +).subscribe(onNext: {print($0)}).addDisposableTo(disposeBag)
Operation Result:
112
Concat
Observable
merges two sequences into a Observable
sequence, and the Observable
elements in another sequence are emitted when all elements of a sequence are successfully launched Observable
.
Before the first Observable
launch is complete, the second Observable
emitted event is ignored, but it receives Observable
Observable
the last event of the second launch before the first one is completed.
Not a good idea, for example:
let disposeBag = DisposeBag() let subject1 = BehaviorSubject(value: "??")let subject2 = BehaviorSubject(value: "??") let variable = Variable(subject1) variable.asObservable() .concat() .subscribe { print($0) } .disposed(by: disposeBag) subject1.onNext("??")subject1.onNext("??") variable.value = subject2subject2.onNext("I would be ignored")subject2.onNext("??") subject1.onCompleted()subject2.onNext("??")
Operation Result:
next(??)next(??)next(??)next(??)next(??)
Explanation: subject1
Before the launch completes the event
variable.value = subject2subject2.onNext("I would be ignored")subject2.onNext("??")
subject2
The emitted events are ignored, but the subject2
last event of the launch is received, and therefore printed onnext(??)
.
Thanks
If you find the wrong place, welcome to comment, thanks!
RxSwift Series (vi)