midnight
midnight

Reputation: 3412

Prevent observables from being started unless another observable finishes it's job

In my app client uses services backed by Observables. Each service call is session based, so that a session has to be started before a business-service method can be called.

In order to init session I made an Observable that does it. My problem is that whenever client uses more than one business-service in parallel, session initialization gets duplicated. Client code is session-agnostic. I need a way to init session in such a way that the session observable only gets called once(when the first business-service method gets called). Basically all subsequent business-observers have to wait for condition(session initialization). Can you draw a pattern for it?

Client code would look like:

protected void onCreate(Bundle savedInstanceState) {
    itemService.getItems(10).subscribe(new Observer<List<Item>>() {..});
    userService.getProfile().subscribe(new Observer<List<Profile>>() {..});
}

While there're 2 calls, I need to make the session Observable execute once only and make business Observables wait for the session initialization to complete and then start doing its' job.

Thanks.

Upvotes: 1

Views: 499

Answers (2)

Andr&#233; Staltz
Andr&#233; Staltz

Reputation: 14004

If the session initialization is an Observable, then you can delay all other Observables that depend on it, using the delay operator with the session initialization Observable as parameter: http://reactivex.io/RxJava/javadoc/rx/Observable.html#delay%28rx.functions.Func1%29

Upvotes: 2

kjones
kjones

Reputation: 5823

Since you already have a session Observable implemented, one possible solution would be to convert it to an AsyncSubject. It would execute only once and would emit only the last item (or only item) to each subscriber.

Depending on how your session initialization code works, it may be more elegant to use one of the Async operators such as Async.start() or Async.startFuture() to create your session observable.

Upvotes: 0

Related Questions