BehaviorRelay and RxProperty

Any Swift developer who worked with RxSwift knows that Observables and Subjects lack the ability to store the last value. Before RxSwift 5.0.0 there was the _Variable _generic class for this purpose, now it has been substituted with the BehaviorRelay which technically is not even part of RxSwift, but RxRelay module.

A developer who just starting to use RxSwift may be confused, what’s the difference between PublishSubjectBehaviorSubjectPublishRelay, and BehaviorRelay.

  • Publish vs _Behavior. _The first doesn’t store the last value, while the last - does.
  • Subject vs Relay. The last doesn’t through an error and can’t be terminated, while the first - can.

As you may already know, RxSwift is used to glue components in the app: a ViewModel with a ViewController in MVVM, an Interactor with Services in RIBs, a Middleware with a Store in Redux.

Normally, a _PublishSubject _is used to propagate an event, while BehaviorRelay to share some value or a state. The common interface for a ViewModel looks like:

There is a slight problem with this ViewModel declaration though: its state is modifiable outside. Because even it is only a get property, ._accept()_method, which modifies the value, is available. This totally breaks one of the fundamental rules of OOP - encapsulation.

Someone may propose to use Observable in the protocol instead of BehaviorRelay, i.e. something like that:

#mvvm #rxswift #ios-app-development #ios #property-wrapper

RxSwift: read-only property and read-write property wrapper
11.30 GEEK