RxSwift: BehaviorRelay over Variable

Romain Bertozzi
Koolicar Engineering
2 min readMar 13, 2018

As many, many iOS developers around the globe, I make use of Reactive programming thanks to RxSwift. And if you are using it too, then you’re used to write Variables.

Well, I learnt recently that this beloved wrapper for BehaviorSubject has fallen into deprecation. This deprecation is in its early stages and no warning will be risen for now. The path is already laid out though, and its successor chosen: BehaviorRelay.

Why?

According to Krunoslav Zaher in his post, for a lot of reasons regarding Variables:

it’s not a standard cross platform concept so it’s out of place in RxSwift target.

it doesn’t have an extensible counterpart for event management (PublishRelay). It models state only.

it is naming is not consistent with *Relay

it has an inconsistent memory management model compared to other parts of RxSwift (complete on dealloc)

So what does that mean for our code?

Well, this:

Variable Way

now becomes:

BehaviorRelay Way

There’s however one last step to complete this migration. Indeed, BehaviorRelay lies in RxCocoa, so an import is needed.

This might seem kind of strange though, to add this import in low-level layers of our apps, where no UI-related components are needed. The question was asked in this issue and “extracting *Relay and SharedSequence into their own frameworks” was suggested by Mr. Zaher here. This whole adventure should come to an end in the next major release of RxSwift.

*Relay classes were introduced with RxSwift 4. This ObservableType can’t terminate with an error or a completed, unlike BehaviorSubject. You can read more about them in this article from Minh Vu Nhat.

In the end

I personally made the decision, and it’s now a standard for the iOS guild at Koolicar, to use BehaviorRelay without delay in the new code I write. Since the deprecation is certain, I think that it’s useful to begin the transition slowly with this brand new code. Concurrently, I try to migrate Variables that I encounter whenever it’s possible and safe during my tasks, if it fits. The idea is to try to smooth the transition as much as possible.

Finally, I’m impatiently waiting for the final answer of the location of BehaviorRelay. I’d love to remove RxCocoa from UIKit-independent entities.

Monday, September 17, 2018: RxSwift developers released their 4.3.0 “RotWeiß” version yesterday. The deprecation of Variable keeps progressing since its usage is now removed from Playgrounds, Example projects and Tests.

Wednesday, July 31, 2019: as stated by Matt Whitlock in the comments, BehaviorRelay now belongs to RxRelay. This transition was completed in RxSwift 5.0.0, released in April, 2019. Thank you Matt!

--

--

Romain Bertozzi
Koolicar Engineering

Hey! I'm a Senior iOS Developer but I also like other stuff. I try to write things, sometimes, but I watch Stargate (maybe too) often.