What if we combine AsyncSubject and PublishSubject? Or mix the benefits of both? BehaviorSubject emits the last item it got before the subscription and all the subsequent items at the time of subscription while working with multicasting, that is, it keeps an internal list of Observers and relays the same emit to all of its Observers without replaying.
Here is the graphical representation which has been taken from ReactiveX documentation (http://reactivex.io/documentation/subject.html):
Let's modify the last example with BehaviorSubject and see what happens:
fun main(args: Array<String>) { val subject = BehaviorSubject.create<Int>() subject.onNext(1) subject.onNext(2) subject.onNext(3) subject.onNext(4) subject.subscribe({ //onNext println("S1 Received $it") },{ //onError it.printStackTrace() },{ //onComplete println("S1 Complete") }) subject.onNext(5) subject.subscribe({ //onNext println("S2 Received $it") },{ //onError it.printStackTrace() },{ //onComplete println("S2 Complete") }) subject.onComplete() }
Here, I took the last example where we worked with AsyncSubject, and modified it with BehaviorSubject. So, let's see the output and understand BehaviorSubject:
S1 Received 4 S1 Received 5 S2 Received 5 S1 Complete S2 Complete
While the 1st subscription gets 4 and 5; 4 was emitted before its subscription and 5 after. For the 2nd subscription, it only got 5, which was emitted before its subscription.