操作符(多个Observable)

2020-07-05  本文已影响0人  fanren

一、merge

let bag = DisposeBag()
let sub1 = PublishSubject<String>()
let sub2 = PublishSubject<String>()
Observable.of(sub1, sub2).merge().subscribe(onNext: { (value) in
    print(value)
}, onError: { (err) in
    print(err)
}, onCompleted: {
    print("success")
}).disposed(by: bag)

sub1.onNext("aa")
sub2.onNext("bb")

let error = NSError(domain: "", code: 1, userInfo: nil)
sub1.onError(error)

sub1.onCompleted()
sub1.onNext("cc")
sub2.onNext("dd")
sub2.onCompleted()
sub2.onNext("ee")

二、concat

let bag = DisposeBag()
let sub1 = PublishSubject<String>()
let sub2 = PublishSubject<String>()
Observable.of(sub1, sub2).concat().subscribe(onNext: { (value) in
    print(value)
}, onError: { (err) in
    print(err)
}, onCompleted: {
    print("success")
}).disposed(by: bag)

sub1.onNext("aa")
sub1.onNext("bb")
sub2.onNext("cc")
sub1.onCompleted()

 //let error = NSError(domain: "", code: 1, userInfo: nil)
 //sub1.onError(error)
sub2.onNext("dd")
sub2.onCompleted()
sub2.onNext("ee")

三、zip

let bag = DisposeBag()
let sub1 = PublishSubject<String>()
let sub2 = PublishSubject<String>()
Observable.zip(sub1, sub2).subscribe(onNext: { (value) in
    print(value)
}, onError: { (err) in
    print(err)
}, onCompleted: {
    print("success")
}).disposed(by: bag)
sub1.onNext("aa")
sub1.onNext("bb")
sub2.onNext("cc")
sub1.onCompleted()
let error = NSError(domain: "", code: 1, userInfo: nil)
sub1.onError(error)
sub2.onError(error)
sub2.onNext("dd")
sub2.onCompleted()
sub2.onNext("ee")
sub1.onNext("ff")

四、combineLatest

let bag = DisposeBag()
let sub1 = PublishSubject<String>()
let sub2 = PublishSubject<String>()
Observable.combineLatest(sub1, sub2).subscribe(onNext: { (value) in
    print(value)
}, onError: { (err) in
    print(err)
}, onCompleted: {
    print("success")
}).disposed(by: bag)
sub1.onNext("aa")
sub2.onNext("cc")
sub1.onNext("bb")
sub1.onCompleted()
sub1.onNext("mm")
//let error = NSError(domain: "", code: 1, userInfo: nil)
//sub1.onError(error)
//sub2.onError(error)
sub2.onNext("dd")
sub2.onNext("ee")
sub2.onCompleted()
sub1.onNext("ff")
上一篇下一篇

猜你喜欢

热点阅读