RxSwift : Observing Operators ✅

Yuvraj Pandey
6 min readAug 13, 2018

If you are from a programming background or have some sort of know how of it, then you must have surely come across the term Reactive which has become very popular in today’s programming world. But if you are not that familiar with it then just sit back and read through the whole to get the grip. Let see what the textual definition say’s about Reactive Programming,

In computing, reactive programming is a programming paradigm oriented around data flows and the propagation of change. This means that it should be possible to express static or dynamic data flows with ease in the programming languages used, and that the underlying execution model will automatically propagate changes through the data flow. — Wikipedia

Now that seemed to be some heavy programming stuff which might have left you with queries but don’t worry and stick around because i will be walking you through some basics in a manner that would definitely make you comfortable with RxSwift so lets begin now.

RxSwift is a framework for interacting with the Swift programming language. This frameworks is designed to be helpful by providing a common vocabulary for certain tasks used repeatedly across different programming languages. This (theoretically) makes it easier to focus on the syntax of the language itself, rather than wasting time figuring out how to map a common task to each new language.

You may ask “Why would I ever want to use it?”. Well, the answer is simple. It just simplifies your work. Instead of notifications, which are hard to test, we can use signals. Instead of delegates, which take a lot of place in code, we can write blocks and remove multiple switches/ifs. We also have KVO, IBActions, input filters, MVVM and many, many more which are handled smoothly by RxSwift. Remember, it’s not always the best way to solve a problem, but you kinda have to know when to use it to its full potential.

1. Observable Sequence

You may think of observable as a think tank of you code that does all the complex work for you which may include a network call, database fetch, background task, huge looping functions and so on. Basic syntax looks like below :

let helloObservable = Observable.just("Hello RxSwift") 

Once you finish with you computation in terms of data fetching or any complex algorithm, now either you need to display the result or pass on to some other function for processing. You can achieve this by using subscribe(on:(Event<T>)-> ()). as follows :

let helloObservable = Observable.just("Hello RxSwift")let subscription = helloObservable.subscribe { event in
print(event)
}

This observable post completion emits the result to subscriber via three functions as follows :

1.next(value: T) — When a value or collection of values is added to an observable sequence it will send the next event to its subscribers as seen above. The associated value will contain the actual value from the observer.

2. error(error: Error) — If an Error is encountered, a observer will emit an error event. This will also terminate the observer.

3. completed — If a observer ends normally it sends a completed event to its subscribers.

let subscription = helloSequence.subscribe { event in
switch event {
case .next(let value):
print(value)
case .error(let error):
print(error)
case .completed:
print("completed")
}
}

If you want to cancel a subscription you can do that by calling dispose on it. You can also add the subscription to a Disposebag which will cancel the subscription for you automatically as follows :

// Creating a DisposeBag so subscribtion will be cancelled correctly
let bag = DisposeBag()
// Adding the Subscription to a Dispose Bag
subscription.addDisposableTo(bag)

2. Basic Operators

Sometimes you want to manipulate, combine or filter the result returned by an observable sequence before the subscriber receives them. The following block will discuss about this basic transformation operators used in reactive programming.

Transforming Operators

1) Buffer

Periodically gather items emitted by an Observable into bundles and emit these bundles rather than emitting the items one at a time.

Buffer Operator

Note that if the source Observable issues an onError notification, Buffer will pass on this notification immediately without first emitting the buffer it is in the process of assembling, even if that buffer contains items that were emitted by the source Observable before it issued the error notification.

2) FlatMap

Transforms the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable. The FlatMap operator transforms an Observable by applying a function that you specify to each item emitted by the source Observable, where that function returns an Observable that itself emits items.

FlatMap Operator

3) Map

The Map operator applies a function of your choosing to each item emitted by the source Observable, and returns an Observable that emits the results of these function applications.

Map Operator

4) Scan

Applies a function to each item emitted by an Observable, sequentially, and emit each successive value. The Scan operator applies a function to the first item emitted by the source Observable and then emits the result of that function as its own first emission

Scan Operator

Filtering Operators

1) Filter

The Filter operator filters an Observable by only allowing items through that pass a condition that you specify in the form of a conditional function.

Filter Opertor

2) DistinctUntilChanged

If you just want to emit next Events if the value changed from previous ones you need to use distinctUntilChanged i.e if you want only the unique data instead of duplicates you can use this operator.

DistinctUntilChanged Operator

3) Debounce

Only emit’s an item from an Observable if a particular timespan has passed without it emitting another item. A perfect example

Debounce Operator.

Combining Observables

1) StartWith

Emit a specified sequence of items before beginning to emit the items from the source Observable. If you want an Observable to emit a specific sequence of items before it begins emitting the items normally expected from it, apply the StartWith operator to it.

StartWith Operator

2) Zip

You use the Zip method if you want to merge items emitted by different observable sequences to one observable sequence. Zip will operate in strict sequence, so the first two elements emitted by Zip will be the first element of the first sequence and the first element of the second sequence combined. Keep also in Mind that Zip will only emit as many items as the number of items emitted of the source Observables that emits the fewest items.

Zip Operator

3) Merge

You can combine the output of multiple Observables so that they act like a single Observable, by using the Merge operator.

Merge Operator

That’s it for this article hope you would have learn something useful from it. So If you have any thoughts or suggestions, feel free to leave a comment below. Don’t forget to share your love by clapping for this article as many times you feel like.

You can follow me on Twitter , Github , LinkedIn , Facebook.

Happy Coding 👨‍💻 🎊.

--

--

Yuvraj Pandey

Working towards striking an impact using technology for making this world a better place to live in ✅