O'Reilly logo

Reactive Android Programming by Tadas Subonis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required