user1831986
user1831986

Reputation: 583

Create BehaviorSubject from Observable

Say I have an observableA which gets data from network and emits it, if I do subscription to this observable each time it tries to request data from network which is heavy.

I want to create BehaviorSubject and connect it to observableA, so that any other threads/objects will subscribe to BehaviorSubject in order to get latest emitted data.

So far I couldnt manage it to code. I cannot create empty BehaviorSubject and call inside observableA, because they are not related to each other. I cannot subscribe to observableA and get BehaviorSubject as observer, any idea how can I accomplish it? or maybe even better?

Upvotes: 10

Views: 6720

Answers (3)

Arun Gopalpuri
Arun Gopalpuri

Reputation: 2493

I had similar scenario in javascript where I wrapped promise within Rx and I didn't want to make network call again when I subscribe to observable. This is how I ended up implementing:

   subject = new Rx.AsyncSubject();
   observable = Rx.Observable.fromPromise(....).subscribe(subject);

You can now consume the promise response as subject.subscribe(...) and it will always emit promise result from subject as we are using AsyncSubject (AsyncSubject - Represents the result of an asynchronous operation. The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers).

Upvotes: 1

Dave Sexton
Dave Sexton

Reputation: 2652

In Rx.NET we'd use one of the Publish overloads that accepts an initialValue parameter. Essentially, it's just a shorter way of doing a multicast like zsxwing described. I'm not sure whether Rx.Java offers these overloaded Publish methods.

Upvotes: 0

zsxwing
zsxwing

Reputation: 20836

You can use multicast. E.g.,

Observable<String> o = ...;
ConnectableObservable<String> co = o.multicast(BehaviorSubject.<String> create());
co.connect();
co.subscribe(...);
co.subscribe(...);
co.subscribe(...);

Upvotes: 4

Related Questions