When we learn a new programming language or new frameworks we always do some mistakes. This is how we people learn things. In this article, I’m want to show you my top 7 mistakes which I did during my Rx trials. I hope I will help you to avoid them 🙂.
#1 – combineLatest vs withLatestFrom
This is the mistake everyone does I think :P. It’s very important to remember
combineLatest sends events when any of its inner Observables sends an event. So… when you want to respond to button tap is the wrong idea to mix it in
If you want to read more what are the differences between
zip you can find an article here 🙂.
#2 – Observable should be lazy
Observable by its nature is a lazy sequence. It shouldn’t run any logic until a subscription. Sometimes you need to wrap an existing API within an Observable:
It’s fine to use
just to wrap a single value. However, you run all the logic to calculate the value before a subscription. If you have used
deferred the calculation would be moved until some Observer subscribes to your Observable:
You can read more about
#3 – Using wrong DisposeBag
DisposeBag is an awesome tool to store multiple
Disposable and dispose them at
deinit. However, it’s crucial to consider when do you want to cancel old subscriptions.
Typical use-case of that is binding the cell with data from CellViewModel:
The above example my looks fine, but there is a big bug inside. Since we’re adding the disposable into
self.disposeBag you gonna have multiple outdated subscriptions when a user starts scrolling the tableView.
You should add the
disposable into cell’s disposeBag and deallocate it on cell reusing (you need to override
#7 – Overusing subjects & variables
Variables and Subjects are a great tool, however, their usage should be limited. I don’t want to say you should avoid them at all cost, however, remember when you use subjects & variables you use a «mutable variables» in Rx world.
Subjects are the «mutable variables» of the Rx world and in most cases you do not need them. – Erik Meijer
Remember that most of the time you can replace Subject with some operators like
defer and many others. If you want to read more when you should use a subject and when you should not I can recommend you this article however it is from Rx.NET world.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters