ReplaySubject

In addition to PublishSubject, which we discussed in the previous section, there are other subjects available. To understand how ReplaySubject works, let's see first the following example with PublishSubject:

val list = (8..23).toList() // Some non trivial numbers
val iterator = list.iterator()
val o = Observable.intervalRange(0, list.size.toLong(), 0, 10, TimeUnit.MILLISECONDS).map {
iterator.next()
}.publish()

val subject = PublishSubject.create<Int>()

o.subscribe(subject)

o.connect() // Start publishing

Thread.sleep(20)

println("S1 subscribes")
subject.subscribe {
println("S1 $it")
}
println("S1 subscribed")

Thread.sleep(10)

println("S2 subscribes")
subject.subscribe {
println("S2 $it")
}
println("S2 subscribed")

Thread.sleep(1000)

This prints the following:

S1 11 <= Lost 8, 9, 10
S1 12
S2 12 <= Lost also 11
S1 13
S2 13
...

Clearly, some events are lost for good.

Now, let's replace PublishSubject with ReplaySubject and examine the output:

val subject = ReplaySubject.create<Int>()

The following output will be printed:

S1 subscribes
S1 8
S1 9
S1 10 <= S1 catchup
S1 subscribed
S1 11
S1 12
S2 subscribes
S2 8
S2 9
S2 10
S2 11
S2 12 <= S2 catchup
S2 subscribed
S1 13 <= Regular multicast from here
S2 13
...

With ReplaySubject, no events are lost. You can see from the output, though, that until some point, events aren't multicast, even when there is more than one subscriber. Instead, for each subscriber, ReplaySubject performs a kind of catch-up of what it missed until now.

The benefits of this approach are clear. We converted what seems to be a hot Observable into something quite cold. But there are also limitations. By using ReplaySubject.create, we produce an unbounded subject. If it tries to record too many events, we will simply run out of memory. To avoid that, we can use the createWithSize() method:

val subject = ReplaySubject.createWithSize<Int>(2)

It creates the following output:

S1 subscribes
S1 9 <= lost 8
S1 10
S1 subscribed
S1 11
S2 subscribes
S1 12
S2 11 <= lost 8, 9, 10
S2 12
S2 subscribed
S1 13
S2 13
...

As you can see, now our subject remembers fewer items, so the earliest events are lost.

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

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