Subjects: Rxjava

Gaurav Rajput
4 min readSep 5, 2020

Subjects act as an observer as well as observable. It means you can call onNext(), onComplete(), and onError() on a Subject, and it will, in turn, pass those events downstream toward its Observers.

Let’s discuss what the types of subjects are and how and where to use them.

PublishSubject:

It’s the simplest form of the subject; there are other subjects that changes its behavior based on their implementation. PublishSubject acts as hot observable. If you don’t know what is hot and cold observable, you can read the following post.

Let’s see how we can create a publish subject. Let’s do for the string.

val basicSubject: PublishSubject<String> = PublishSubject.create()

now this basicSubject is an observable, we can subscribe to it and receive the emitted strings.

val observer = basicSubject.subscribe({
Log.d(TAG, "received string:= $it")
}, {
it
.printStackTrace()
})

Now let’s call onNext on observable:

basicPublishSubject.onNext("hello")
basicPublishSubject.onNext("Kotlin")
basicPublishSubject.onComplete()

Output:

received string:= hello
received…

--

--