RxSwift - Imtiaz211/interviews GitHub Wiki
What is RxSwift?
RxSwift
is a framework for interacting with the Swift programming language, whileRxCocoa
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
orDictionaries
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 ofSubjects
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 aReplaySubject
, you can define how many recent items you want to emit to new subscribers.
Variable
A
Variable
is just aBehaviourSubject
wrapper 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 Observer
is automatically unsubscribed from what it was observing. This allowsARC
to take back memory as it normally would.- Without a
DisposeBag
, you’d get one of tworesults
. Either theObserver
would create aretain cycle
, hanging on to what it’s observing indefinitely, or it could be deallocated, causing a crash.- 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.