Nick
Nick

Reputation: 3435

Start subscription after another subscription fires

There are two observables: a and b. I want to subscribe to the second observable (b) after first observable (a) has fired (i.e. has generated very first onNext event).

I tried

    b.skipUntil(a).subscribe(onNext:{
        print("B: \($0)")
    }).disposed(by: _bag)

but with no luck because b is a cold observable. As I understand, it starts immediately and gets blocked by skipUntil(a).

This approach seems to work:

    a.subscribe(onNext:{_ in
        // ... handle a ...

        b.subscribe(onNext:{
            print("B: \($0)")
        }).disposed(by: self._bag)
    }).disposed(by: _bag)

but I realise this is a bad practise and not a way to go.

Upvotes: 1

Views: 115

Answers (1)

Daniel T.
Daniel T.

Reputation: 33967

That's a simple flatMap:

let c = a.flatMap { _  in b }

You might want to add a .take(1) before the flatMap or look over the different varieties of flatMap and see which one is right for your use case. And it would be best to generate the b observable inside the flatMap closure instead of passing it in like the above.

https://medium.com/@danielt1263/rxswifts-many-faces-of-flatmap-5764e6c2018c

Upvotes: 1

Related Questions