RxSwift - Imtiaz211/interviews GitHub Wiki

What is RxSwift?

RxSwift is a framework for interacting with the Swift programming language, while RxCocoa is a framework that makes Cocoa APIs used in iOS and OSX easier to use with reactive techniques. ReactiveX frameworks provide a common vocabulary for tasks used repeatedly across different programming languages.

Observable Sequences

The first thing you need to understand is that everything in RxSwift is an observable sequence or something that operates on or subscribes to events emitted by an observable sequence. Arrays, Strings, Set or Dictionaries will be converted to observable sequences in RxSwift.

Subjects

A Subject is a special form of an Observable Sequence, you can subscribe and dynamically add elements to it. There are currently 4 different kinds of Subjects in RxSwift.

PublishSubject

If you subscribe to it you will get all the events that will happen after you subscribed.

BehaviourSubject

A behavior subject will give any subscriber the most recent element and everything that is emitted by that sequence after the subscription happened.

ReplaySubject

If you want to replay more than the most recent element to new subscribers on the initial subscription you need to use a ReplaySubject. With a ReplaySubject, you can define how many recent items you want to emit to new subscribers.

Variable

A Variable is just a BehaviourSubject wrapper that feels more natural to a non reactive programmers. It can be used like a normal Variable.

What is disposeBag?

  1. Used to avoid memory leaks as the subscription will not be disposed of correctly without.
  2. DisposeBag holds disposables.
  3. DisposeBag allows us not to have to dispose of each subscription individually.
  4. Used with the .addDisposableTo() operator which will call dispose() on each when the dispose bag is about to be deallocated.
  5. When deinit() is called on the object that holds the DisposeBag, each disposable Observer is automatically unsubscribed from what it was observing. This allows ARC to take back memory as it normally would.
  6. Without a DisposeBag, you’d get one of two results. Either the Observer would create a retain cycle, hanging on to what it’s observing indefinitely, or it could be deallocated, causing a crash.
  7. To be a good ARC citizen, remember to add any Observable objects to the DisposeBag when you set them up. The DisposeBag will clean up nicely for you.