Nikita Ermolenko
Nikita Ermolenko

Reputation: 2259

Merge observables on one type and then chain to obserbable of another type

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

Answers (2)

Nikita Ermolenko
Nikita Ermolenko

Reputation: 2259

I implemented this by takeLast(1) and then flatMap to needed Observable.

Upvotes: 0

solidcell
solidcell

Reputation: 7729

The type of Element needs to be known, so you have a few options I can think of:

  1. Make the type Any, which both Int and String can be.
  2. Add protocol conformance to Int and String which can expose the common interface you're wanting to use on them.
  3. Make the type an enum which has cases for both Int and String.

Here's an implementation of each of those options:

With Any:

let withAny = PublishSubject<Any>()

withAny.subscribe(onNext: { print($0) })
    .addDisposableTo(disposeBag)

withAny.onNext(1)
withAny.onNext("a")

1
a

With some 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

With some 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

Related Questions