Intro to RxSwift (part 2)

Hi there, this is a continuation of my previous post dedicated to RxSwift. As I told you, you’ll need to know a few things to understand Reactive Extensions: Observables, Subscriptions, Subjects, Operators, Schedulers. We already covered Observables and Subscriptions, now are going to talk about Subjects. If you never read that article I encourage you to do that.

Subjects:

We already learned about observables and observers(subscriptions). But probably, you had a thought that observables are kind of “straightforward” and you can not add events to observables stream once you create them. So here comes the Subjects. Subjects act as both an observable and an observer, where you can add events to an existing observable stream. And there are 4 types of Subjects which we going to cover: PublishSubject, BehaviorSubject, ReplaySubject, Variable.

PublishSubject

Publish subjects used when you want subscribers to be notified only of new events from the point at which they subscribed. By saying new events I mean only new events. Even if observable emitted events before and someone subscribed to it at some point, it won’t get previous events, only wait for new events. Here is some code to try:

We create PublishSubject publish and create subscription1 for it. And then we add value 10 to publish observable stream. Next, we create subscription2 for publish observable. And again add a new value 20 to publish observable stream. Guess what is the output?

Swift

1

2

3

4

5

6

Subscription1:next(10)

Subscription1:next(20)

Subscription2:next(20)

Subscription1:next(30)

Subscription2:next(30)

Subscription3:next(30)

We can see that subscription2 did not get the previous value 10, but it received all new coming values. Pretty easy. The very common case for using it in real app development is handling button taps. PublishSubject observes button touches, and subscribers will get only new touches because most likely they do not need to know if the button was tapped before.

BehaviorSubject

BehaviorSubject almost the same as PublishSubject, with one exception: new subscribers will get the last emitted event.

We use almost the same example we did with PublishSubject, but this time using String values. And since BehaviorSubject always returns last emitted values to new subscribers it has to have the initial value. In this example, we create BehaviorSubject with the initial OnNext event with the String value “Hi”. Then we create subscriptions for that subject. As you can see besides onNext event, we used the onCompleted event which completes the stream. And after that, we tried to emit the new onNext event. You can guess what the output will be.

Swift

1

2

3

4

5

6

Subscription1:next(Hi)

Subscription1:next(How are you?)

Subscription2:next(How are you?)

Subscription1:completed

Subscription2:completed

Subscription3:completed

So, this time new subscribers got previous values at the point of subscription. subscription1 got the initial value of the behavior, as well as next subscriptions, got the event the observable emitted before. And also, as you can see once subject emitted the onCompleted event, the stream terminated and all subscriptions stopped receiving any events. That’s why we didn’t get onNext(“Hey”) event.

The good example in real app development would be observing a text entry by BehaviorSubject and have multiple subscriptions to work with that text.

Variable

The Variable wraps a BehaviorSubject and stores its current value as a state. Which means you can access the last emitted value of the subject without subscribing to it, just by calling value property of the subject. That value got from the unwrapped onNext event, which means Variable is guaranteed not to emit the onError event. And you can not manually push onCompleted event, only if a variable is deallocated.

We create a Variable of type Bool with the initial value of “false”. Then subscribe to that variable and print some text. Next, we change the value of the variable, note that subscriber gets that change. And finally, we print some text access the value of the variable.

Swift

1

2

3

Subscription1:next(false)

Subscription1:next(true)

Ijust printed that variable istrue

As you can see Variable is convenient using it both as Observable and as regular value. You might be using this type of subject a lot.

ReplaySubject

ReplaySubject is quite a simple one. Remember that BehaviorSubject returns only one last emitted event? So replay subject almost the same with one small difference, you can adjust the number of last events you want to get. And think about the buffer when we talking about that.

Here we create a ReplaySubject of type Int with buffer size 3. Then we create subscription1 for it, at this point observable didn’t emit any events, and subscription1 will get all future events. We push some events to replay subject and create a new subscription. So guess what values will subscription2 print?

Swift

1

2

3

4

5

6

7

Subscription1:next(0)

Subscription1:next(5)

Subscription1:next(9)

Subscription1:next(8)

Subscription2:next(5)

Subscription2:next(9)

Subscription2:next(8)

Subscription1 gets all events even if the number of events is less than the buffer size. And Subsciption2 gets only last 3 events, it didn’t print next(0) event. This subject is useful when you need not only last value but also values before last.

Disposables

In my first article about RxSwift, you probably noticed weird word Disposable in the example code. So as I promised you, I’d like to explain to you what Disposables are before moving forward. So, the word disposable speaks for itself. The purpose of disposing to release subscriptions out of memory. And even if Observable is still alive and emits some evens, disposed subscriptions will not get that event. The easiest way to deallocate subscription is to call Dispose method.

Swift

1

2

3

4

5

letbehavior=BehaviorSubject<Int>(value:0)

letsubscription=behavior.asObservable().subscribe{print($0)}

behavior.onNext(5)

subscription.dispose()

behavior.onNext(10)

We create a BehaviorSubject and subscription to it. Push some value to the stream, and then we Dispose the subscription. And push some value again. The output:

Swift

1

2

next(0)

next(5)

So, as you can see it didn’t print 10 value because the subscription was deallocated. And if you need to perform actions on deallocation, subscribe(onDespose: ) can handle that.

Swift

1

2

3

4

5

6

7

8

9

letpublish=PublishSubject<String>()

letsubscription=publish.asObservable().subscribe(onNext:{(value)in

print(value)

},onDisposed:{

print("The subscription was disposed")

})

publish.onNext("Hi")

subscription.dispose()

publish.onNext("How are you?")

We create PublishSubject and subscription to that subject where we sort events by onNext and onDisposed event. We push onNext event and dispose the subscription. The output is:

Swift

1

2

Hi

The subscription was disposed

And here as well it didn’t print any values after disposing.

You are probably wondering about the case where you will have a lot of subscriptions, and would that mean that you have to dispose every single of them? The answer is no. RxSwift provides a powerful functionality to manage that. It is called DisposeBag. You will put your subscriptions into DisposeBag, and once your dispose bag deallocates all subscriptions in it deallocates too. Here is the simple example of it. Usually, you would handle releasing action callbacks from the array in some weird way. I would like to show two versions of code without and with RxSwift, and power of Disposables.

Swift

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

classCat{

init(){

Person.shared.onEnter{[weakself]in

guard letcat=selfelse{returnfalse}

print("Meaw")

returntrue

}

Person.shared.entered=false

}

}

classPerson{

staticletshared=Person()

typealiasCallback=()->Bool

private varenterCallbacks:[Callback]=[]

varentered:Bool=false{

didSet{

foriin(0..<enterCallbacks.count).reversed(){

if!enterCallbacks[i](){

enterCallbacks.remove(at:i)

}

}

}

}

funconEnter(callback:@escaping Callback){

enterCallbacks.append(callback)

}

}

iftrue{

letcat=Cat()

}

Person.shared.entered=false

We have 2 classes Cat and Person. Cat as usually does nothing, except making “Meaw” sounds once a person comes in. And Person has entered property which informs if Person entered the room. Also, it has private callbacks which execute on entered value change, callback returns a Bool value which tells if the callback has to be released from memory. This is the nasty mechanism of releasing callback from memory, but it’s a common practice. With RxSwift you can handle it with DisposeBag.

First, you can see it takes less code, to perform the same task. Second, it’s optimized because in previous example callbacks did not release from memory until they execute. So, once the Cat object deinits subscription will be destroyed too.

In the next article, we are going to cover a huge and important theme: Operators. So subscribe to be notified of new upcoming articles.