Reputation: 2259
Are there solutions for chaining Observables of different types?
I want to merge
Observables, and when each of them sends the Completed
event, emit the next Observable (signal
).
Something similar to ReactiveCocoa
's then
.
let signal = Observable<String>.create { observer in
observer.onCompleted()
return Disposables.create()
}
let signals: [Observable<Int>] = [Observable.just(1), Observable.just(2), Observable.just(3)]
Observable.from(signals).merge().concat(signal).subscribe {
print("completed")
}
Upvotes: 2
Views: 92
Reputation: 2259
I implemented this by takeLast(1)
and then flatMap
to needed Observable.
Upvotes: 0
Reputation: 7729
The type of Element
needs to be known, so you have a few options I can think of:
Any
, which both Int
and String
can be.Int
and String
which can expose the common interface you're wanting to use on them.enum
which has cases for both Int
and String
.Here's an implementation of each of those options:
Any
:let withAny = PublishSubject<Any>()
withAny.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
withAny.onNext(1)
withAny.onNext("a")
1
a
protocol
:protocol SomeProtocol {
// put whatever interface from the elements in here
}
extension String : SomeProtocol {}
extension Int : SomeProtocol {}
let withProtocol = PublishSubject<SomeProtocol>()
withProtocol.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
withProtocol.onNext(2)
withProtocol.onNext("b")
2
b
enum
:enum SomeEnum {
case int(Int)
case str(String)
}
let withEnum = PublishSubject<SomeEnum>()
withEnum.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
withEnum.onNext(.int(3))
withEnum.onNext(.str("c"))
int(3)
str("c")
Upvotes: 2