BehaviorSubject

BehaviorSubject is very similar to PublishSubject. However, there is a slight difference in the behavior when somebody subscribes to the Subject. While PublishSubject just relays the received items to its subscribers after they've subscribed, the BehaviorSubject emits one value to the subscriber that was the last to arrive at the Subject before subscription.

Let's look at an example:

Subject<String> subject = BehaviorSubject.create();

Observable.interval(0, 2, TimeUnit.SECONDS)
.map(v -> "A" + v)
.subscribe(subject);

subject.subscribe(v -> log(v));

Observable.interval(1, 1, TimeUnit.SECONDS)
.map(v -> "B" + v)
.subscribe(subject);

Here, the BehaviorSubject subscribes to the first Observable by calling this:

Observable.interval(0, 2, TimeUnit.SECONDS)
.map(v -> "A" + v)
.subscribe(subject);

Then, we start listening to the values emitted by the subject itself by starting the subscription:

subject.subscribe(v -> log(v));

Finally, we subscribe the subject to the last Observable:

Observable.interval(1, 1, TimeUnit.SECONDS)
.map(v -> "B" + v)
.subscribe(subject);

The output of this chain is as shown:

main:A0
RxComputationThreadPool-2:B0
RxComputationThreadPool-1:A1
RxComputationThreadPool-2:B1
...

This shows that as soon as the following line was executed, the subject emitted a value that was already present in the Subject (A0):

subject.subscribe(v -> log(v));

Afterward, when the new items were streamed into the subject, they were all printed out as it would have been in PublishSubject.

The way BehaviorSubject works makes it a perfect candidate to store and retrieve configuration options, for example, authentication credentials. As soon as you subscribe, it will recover the last known value, and if there are any changes, it will emit a new one.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.78.136