If you are an iOS Developer then you should have heard about RxSwift. It’s a swift version of Reactive programming. RxSwift is so powerful and effective that it will do all the work for you in code and make your life easy as a developer.
Don’t Believe? Then you might check this introduction of Reactive Programming to agree with me 🙂
RxSwift is roaming around the following terms:
- Observables & Observers
let’s start exploring all these stuff one by one.
Observables & Observers:
“ Event-A is emitting some data and other events (for example Event-B & Event-C) who subscribes to Event-A will get that emitted data. The event that emits the data (Event-A in this case) is called “Observable” or “Observable sequences” and all events (Event-B & Event-C in this case) that receives emitted data are called “Observers” .”
This is the most simple definition to understand Observable.
Observable data can be continuous or emit in more than one instance. Observers can receive all these instances one by one in sequence.
Let’s check the below diagram:
Here is how the coding representation in swift for the above diagram:
The lifecycle of Observable:
Observables consist of three main events:
two points to remember here:
(1) When observable emits the one element of data which is known as the Next event. In the above case, Observable A is emitting the data for six times. So observers will get that next event one by one.
(2) When observable will complete all the next event it will either terminate with completion or error.
Let’s check some examples:
If you are developing some serious apps than you should really care about memory leaks. So for that Observable has one important aspect which is known as “Dispose Bags”.
Once observable are done with all the next events and terminated at the end, we need to release all the used resources to avoid memory leaks. For that, we need to dispose of subscription.
If you want to get more idea about how can you use this concept to make your code better, Here is some more conceptual things you can try: