我应该如何在RxSwift中合并两种不同类型的Observable?
例如:
var a: Observable<Int> var b: Observable<Void>
由于类型参数不同,Observable.of(a,b).merge()是不可能的.
要合并它们,它们需要为其Element具有相同的类型.
因此,一种选择是抛弃它们的类型信息并转换为AnyObject.现在他们可以合并:
let stringSubject = PublishSubject<String>() let stringObservable = stringSubject.asObservable().map { $0 as AnyObject } let intSubject = PublishSubject<Int>() let intObservable = intSubject.asObservable().map { $0 as AnyObject } Observable.of(stringObservable,intObservable).merge() .subscribeNext { print($0) } .addDisposableTo(disposeBag) stringSubject.onNext("a") stringSubject.onNext("b") intSubject.onNext(1) intSubject.onNext(2) stringSubject.onNext("c")
输出:
a
b
1
2
c
另一个选择是在枚举中包装:
enum Container { case S(String) case I(Int) } let stringSubject = PublishSubject<String>() let stringObservable = stringSubject.asObservable().map { Container.S($0) } let intSubject = PublishSubject<Int>() let intObservable = intSubject.asObservable().map { Container.I($0) } Observable.of(stringObservable,intObservable).merge() .subscribeNext { e in switch e { case .S(let str): print("next element is a STRING: \(str)") case .I(let int): print("next element is an INT: \(int)") } } .addDisposableTo(disposeBag) stringSubject.onNext("a") stringSubject.onNext("b") intSubject.onNext(1) intSubject.onNext(2) stringSubject.onNext("c")
输出:
next element is a STRING: a
next element is a STRING: b
next element is an INT: 1
next element is an INT: 2
next element is a STRING: c
对于可以组合不同类型的Observable的其他运算符(如zip和combineLatest),没有一个像merge一样工作.但是,检查一下.它们可能更适合您的要求.