top of page
  • Writer's pictureJennifer 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.


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)
"relay: " next(Pocoyo?)


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: " next(Hello?)
"brelay: " next(Pocoyo?)

81 views0 comments

Recent Posts

See All


bottom of page