RxSwift Part 3

Ali Akhtar
7 min readJan 16, 2020

--

https://utemissov.com/intro-to-rxswift-part-3/

This is the continuation of previous part 2. In this part we will cover

  1. share operator in details
  2. share(replay:)
  3. empty operator
  4. do operator
  5. How to create your own operator
  6. Throttle
  7. Debounce

share

share operator when we need the chain of operators not to re-execute upon every subscription. Thus, everything before share is executed only once 😕

As shown in Figure “Creating observable…” is called twice because create method gets executed as many times as we subscribe

Figure 1

As shown in Figure 2 by using share operator now “Creating observable…” is called only one time and the observable is now share between all subscribers As the data emitted . by observable it will send to al observer as usual

Figure 2

One point to note if the observable is shared and there is no subscription attached or previous subscription is disposed then chain of operators re-execute for next subscription as shown in Figure 3

Following actions are performed

  1. Created a shared observable
  2. Subscribed first Observer and wait for it’s event, It emit next and completed since complete event dispose the subscription now there is no observer observing
  3. After that we tap on button and on its action we again want to subscribe the shared observable since no previous subscription is there it will again re execute the chain of operators
Figure 3

As shown in Figure 4 there are few things to be note

  1. Since second observer subscribed after first subscription get 1,2 and 3 next events so it will not get these. It will get the next event after thhe subscription
  2. There is only one “Creating observable…” printed on the console since first subscription didn’t dispose yet and (No complete event called)
Figure 5

Question is How to get previous next event emitted before the second subscription and the answer to give parameter value to share operator. As shown in Figure 6 second observer subscribed after first subscription still it get 1,2 and 3 next events that were emitted before it subscribed

Figure 6

One more twist we added .forever as a scope while creating share observable which has the following means

  1. First subscription disposed by calling complete event and second observer subscribed after that with .forever it will not re-execute create method and with the replay 3 it will get previous 3 next event that were emitted before it subscribed

Note: In Rx 3.x behavior of `shareReplay` is used instead of share with parameter replay. In case old 3.x behavior of `shareReplay` is required please use `share(replay: 1, scope: .forever)` instead.”)

Figure 7

Empty

Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.

As shown in Figure 8 it create an Observable that emits no items and immediate terminates

Figure 8

Custom Operator (Creating Own Operator)

As shown in Figure 9 we created a BehaviorSubject of type Optional String , If we want only unwrap value there is no operator to unwrap any observable sequence

Figure 9

We can solve this problem by doing two steps first filter nil observable value and then unwrap value of optional

As shown in Figure 8 we created Observable Type extension that return not nil values from the observable sequence. This method has following things

  1. Restricted to Observable having Optional data Type (where E == T?)
  2. Return Observable of unwrap Observable sequence. It should return Observable sequence because this operator we applying to observable.

“Operators are method that apply to observable sequence and return another immutable observable sequence.”definition we discussed in part 2

Figure 8

A shown in Figure 9 we replaced the filter and map operator with only one operator that can be part of Observable method which reduces code duplication, it is maintainable and testable as well

Figure 9

do

Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence

As shown in Figure 10 we registered callbacks that ReactiveX will call when certain events take place on an Observable by using do operator, where those callbacks will be called independently from the normal set of notifications associated with an Observable cascade. It is used to provide the side effects before sending actual events to its subscriber
onNext → Action to invoke for each element in the observable sequence.
onError → Action to invoke upon errored termination of the observable sequence.
onCompleted → Action to invoke upon graceful termination of the observable sequence.
onSubscribe → Action to invoke before subscribing to source observable sequence.
onSubscribed → Action to invoke after subscribing to source observable sequence.
onDispose → Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed.

Figure 10

throttle

Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration. This operator makes sure that no two elements are emitted in less then dueTime

In Figure 11 we are doing following things

  1. On every Button press observable emit 2 to the observer
  2. Within 10 sec I tapped many times since we define due time to 2sec, throttle operator will bypass these next event until due time reached and when due time reached it will pick the last emitted value and send it to the subscriber
Figure 11
Throttle
https://medium.com/fantageek/throttle-vs-debounce-in-rxswift-86f8b303d5d4

debounce

Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers 😕

In figure 12 I continuously tapped on the button for 12 seconds but nothing is printed on the console because on every click it will emit the next event that will reset the timer .

Figure 12

As shown in Figure 13 after button press I waited for 2 second now it reached the due time and printed the last emitted value. This operator is very helpful if you developing search feature like when user stop filling the text field with some specified time then api hit.

Figure 13

Throttle → the original function be called at most once per specified period.
Debounce → the original function be called after the caller stops calling the decorated function after a specified period.

Useful Links

--

--

Ali Akhtar
Ali Akhtar

Written by Ali Akhtar

Senior iOS Engineer | HungerStation | Delivery Hero

No responses yet