• Jennifer Eve Vega

RxSwift: Relays



One thing that sets relay apart from observables and subjects is that relays never terminate. So when you want to emit new values to the subscribers using relays, you will have to use accept(_:) instead of onNext(_:)


A PublishRelay wraps a PublishSubject, and a BehaviorRelay wraps a BehaviorSubject.


And before you could start using relays, make sure to import RxRelay together with import RxSwift.


PublishRelay

Initialized without any initial value

let pRelay = PublishRelay<String>()
pRelay.accept("Hello?") // Not emitted because there are no subscribers yet
            
pRelay.subscribe { (value) in
     debugPrint("relay: ", value)
}
.disposed(by: bag)
            
pRelay.accept("Pocoyo?")
"relay: " next(Pocoyo?)

BehaviorRelay

Initialized with an initial value. This value (or the latest value) will be replayed to the new subscribers.

let bRelay = BehaviorRelay<String>(value: "Hi")
bRelay.accept("Hello?") // this will be emitted because this is the last value
            
bRelay.subscribe { (value) in
      debugPrint("brelay: ", value)
}
.disposed(by: bag)
            
bRelay.accept("Pocoyo?")
"brelay: " next(Hello?)
"brelay: " next(Pocoyo?)

18 views0 comments

Recent Posts

See All