Subject

The easiest way to understand Subject is that Subject = Observable + Observer.

On the one hand, it allows others to subscribe() to it. On the other, it can subscribe to other Observable:

val dataSource = Observable.fromIterable((1..3))

val multicast = PublishSubject.create<Int>()

multicast.subscribe {
println("S1 $it")
}

multicast.subscribe {
println("S2 $it")
}

dataSource.subscribe(multicast)

Thread.sleep(1000)

The following code prints six lines, three for each subscriber:

S1 1
S2 1
S1 2
S2 2
S1 3
S2 3

Note that we didn't use publish() on our dataSource, so it's cold. Cold means that each time somebody subscribes to this source, it will begin sending data anew. The hot Observable, on the other hand, doesn't have all the data, and will only send what it has from this moment on.

For that reason, we need to first connect all the listeners, and only then begin to listen to the dataSource.

If we're using a hot dataSource, we can switch the calls:

val dataSource = Observable.fromIterable((1..3)).publish()

val multicast = PublishSubject.create<Int>()

dataSource.subscribe(multicast)

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

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

dataSource.connect()

Thread.sleep(1000)

As in the previous section, we use connect() to tell dataSource when to start emitting data.

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

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