RXSwift Basics with Story

Subject – Observable and Observer at once. Basically it can observe and be observed.
BehaviorSubject – When you subscribe to it, you will get the latest value emitted by the Subject, and then the values emitted after the subscription.
PublishSubject – When you subscribe to it, you will only get the values that were emitted after the subscription.
ReplaySubject – When you subscribe to it, you will get the values that were emitted after the subscription, but also values that were emitted before the subscription. How many old values will you get? It depends on the buffer size of ReplaySubject you subscribe to.

You’ve opened first, second, third gift. And whoops! Your mom was cooking some delicious food and is late to the opening party. As a mom, she just has to know what presents you’ve got already. So you tell her about them. In Rx world you’ve sent observable sequence (presents) to the observer (your mom). What’s interesting is that she started observing you after you already emitted few values, but she got whole info anyways. For her we are a ReplaySubject with buffer = 3 (we save 3 latest presents and give it every time a new subscriber appears).

You are still opening presents and there you see that two of your friends (Jack and Andy) were also late to the party. Jack happens to be your close friend so he asks what have you opened so far. As you are kinda angry that he missed a part of it, you tell him only the latest present you’ve opened. He doesn’t know that there were more of it, so he is happy with it. In Rx world you’ve sent only latest emitted value to the observer (Jack). He will also get the next values as you emit them (next presents you will open). For him we are a BehaviorSubject (we kinda changed the Subject ?).

There is also Andy, who happens to be just a friend and doesn’t really care about the presents you’ve opened so he just sits down and waits for the rest of the show. As you can imagine, for him we are just a PublishSubject. He just gets values that are emitted after the subscription.

One more thing...

There is also something called Variable. This is wrapper around BehaviorSubject. The thing is, you can only submit the .onNext() event (when using BehaviorSubject you have direct access to sending .onError().onCompleted()). Also, Variableautomatically sends .onCompleted() event when it’s being deallocated.

Alright, enough with definitions. Let’s try it out!

Source: https://www.thedroidsonroids.com

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

« »

Keep Better In The Life