0

I have a special need for an observable.

Usually, my observables run in a different thread. But, sometimes they need to block another thread in the middle of subscription. Something the way a future behaves.

An example:

val o = Observable.create(/* computation */)
  .subscribeOn(Schedulers.newThread())
  .observeOn(/* current thread */);

val s = o.subscribe(/* subscriber */);`

Suddenly, an event happens on yet another thread that signals the current thread that it should wait for the execution of the subscription s. (An example would be Android's onPause.)

How do I do that? How do I wait on the subscription s and even possibly retrieve all of the results?

(Subjects?)

stojanman
  • 325
  • 3
  • 15
  • `o.toBlocking()` is kind of equivalent to `future.get()` – Vladimir Mironov Aug 07 '15 at 16:18
  • @VladimirMironov yes but that is *before* I subscribe to the observable. What I need is after subscription. So basically, no double computations. – stojanman Aug 07 '15 at 16:24
  • Maybe a serialized ReplaySubject could do the trick. Essentially you convert the subject to an Observable, and then that to a blocking one... or subscribe to that observable on the immediate thread. – stojanman Aug 07 '15 at 16:26
  • ... or take care to cache the results in the original observable, and then just subscribe on the immediate thread. – stojanman Aug 07 '15 at 16:28
  • I see there is an `Observable#cache()` method. That is probably the simplest solution. – stojanman Aug 07 '15 at 16:29

1 Answers1

0

The simplest solution for this seems to be:

  1. Make the observable be a caching one with Observable#cache(). (If your observable is a stream of values, use an appropriate Subject and use that as the observable.)
  2. Subscribe to the cached observable / subject.
  3. When the event occurs, simply subscribe to the cached observable / subject on the thread(s) you require. Cancel the subscription as appropriate.
stojanman
  • 325
  • 3
  • 15