RxSwift — Subjects

Khuong Pham
Indie Goodies
Published in
2 min readJul 7, 2017

When you diving in RxSwift, you need to overview of Subjects. So what is Subjects?

Subjects act as both an observable and an observer. They can receive events and also be subscribed to. The subject received .next events, and each time it received an event, it turned around and emitted it to its subscriber.

There are 4 subject types in RxSwift:

PublishSubject: Starts empty and only emits new elements to subscribers.

BehaviorSubject: Starts with an initial value and replays it or the latest element to new subscribers.

ReplaySubject: Initialized with a buffer size and will maintain a buffer of elements up to that size and replay it to new subscribers.

Variable: Wraps a BehaviorSubject, preserves its current value as state, and replays only the latest/initial value to new subscribers.

This part is focus on PublishSubject

A picture is worth a thousand words

The first subscriber subscribe after 1, so it doesn’t get that event, it receives 2 and 3. The second subscriber subscribe after 2, so it only receives 3.

Practicing is worth a ten thousand words ( :D )

Let’s say we have a PublishSubject of type String

let subject = PublishSubject<String>()

Trying emitting an event:

subject.onNext(“No event emitted??”)

Nothing prints out??

Yes, because there is none of subscriptions on this subject.

let’s create a subscription:

let subscriptionOne = subject                          .subscribe(onNext: { string in                              print("First Subscription: ", string)                          })

Now use subject to emit item

subject.onNext("1")subject.onNext("2")

Definitely, the output print out 1 and 2.

Now, let's create another subscription:

let subscriptionTwo = subject                         .subscribe({ (event) in                             print("Second Subscription: \(event)"))                          })

and trying emitting event:

subject.onNext("3")

This will notify on subscriptionOne and subscriptionTwo that subject emits 3, they listen and then do their printing action.

First Subscription:  3Second Subscription: next(3)

Next, we trying dispose subscriptionOne and emit 4

subscriptionOne.dispose()subject.onNext("4")

Only subscriptionTwo can do printing action, because subscriptionOne resource was disposed.

Second Subscription: next(4)

Finally, trying emitting complete event and since we don’t use subscriptionTwo anymore, we should dispose it.

subject.onCompleted()subscriptionTwo.dispose()subject.onNext("Any event emitted??")

Complete event will be printed out:

Second Subscription: completed

Here is full of code and output:

^_^ That’s it!!

Support my apps

https://indiegoodies.com/breather

--

--