iammini
iammini

Reputation: 303

Flatmap my observable to subject

The question is a little tricky.

I am trying to implement the observable interface, within it i need to start listen to another publicsubject once the observable meet some circustance, so i write some code like this:

public myAPI(){
   return  restAPI.call()
                .flatmap{ ret ->
                   if(ret == success) return myPublishSubject
                 }

can it guarantee the subscribe start subscribe to the publishsubject only after restAPI call is done successfully ?

Upvotes: 1

Views: 488

Answers (1)

akarnokd
akarnokd

Reputation: 69997

The flatMap's Function callback is invoked when there is a value from upstream, in this case, the restAPI.call().

However, note that mapping to a PublishSubject late can result in items being missed. To avoid such problems, you can consider using BehaviorSubject that retains the last item it received so the flatMap can emit immediately upon subscribing to it.

In addition, repeatedly mapping to the same Subject can result in memory leaks and item duplication. Unfortunately, you'd have to complete the Subject in order to release it, but then it becomes unusable for dispatching further events. takeUntil may help in this case though.

Upvotes: 1

Related Questions