Top mistakes in RxSwift you want to avoid

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 combineLatest.

If you want to read more what are the differences between combineLatestwithLatestFrom and 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 createjust & deferred here

#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 prepareForReuse):

#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 mergeconcatpublish & refCountdefer 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.

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión /  Cambiar )

Google photo

Estás comentando usando tu cuenta de Google. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s