RxSwift - Imtiaz211/interviews GitHub Wiki
What is RxSwift?
RxSwiftis a framework for interacting with the Swift programming language, whileRxCocoais 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,SetorDictionarieswill be converted to observable sequences in RxSwift.
Subjects
A
Subjectis a special form of an Observable Sequence, you can subscribe and dynamically add elements to it. There are currently 4 different kinds ofSubjectsin RxSwift.
PublishSubject
If you subscribe to it you will get all the events that will happen after you subscribed.
BehaviourSubject
A
behaviorsubject 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 aReplaySubject, you can define how many recent items you want to emit to new subscribers.
Variable
A
Variableis just aBehaviourSubjectwrapper that feels more natural to a non reactive programmers. It can be used like a normal Variable.
What is disposeBag?
- Used to avoid memory leaks as the subscription will not be disposed of correctly without.
- DisposeBag holds disposables.
- DisposeBag allows us not to have to dispose of each subscription individually.
- Used with the
.addDisposableTo()operator which will calldispose()on each when the dispose bag is about to be deallocated.- When
deinit()is called on the object that holds theDisposeBag, eachdisposable Observeris automatically unsubscribed from what it was observing. This allowsARCto take back memory as it normally would.- Without a
DisposeBag, you’d get one of tworesults. Either theObserverwould create aretain cycle, hanging on to what it’s observing indefinitely, or it could be deallocated, causing a crash.- To be a good
ARCcitizen, remember to add any Observable objects to the DisposeBag when you set them up. The DisposeBag will clean up nicely for you.