RxCocoa - Why doesn't PublishRelay have an asDriver() method?
Asked Answered
E

2

12

On RxCocoa I was wondering why the PublishRelay doesn't have an asDriver() method like the BehaviorRelay ? Currently if I want to convert the publishRelay into a Driver, I have to specify what to return in case of error which seems weird given that the relays can't generate errors...

Elliellicott answered 29/1, 2019 at 17:6 Comment(0)
G
28

Those two versions of ...Relay are used to model different concepts:

  • BehaviorRelay represents State
  • PublishRelay represents Events

It makes sense to replay State, hence BehaviorRelay replays its latest value.

It makes less (no?) sense to replay Events, hence PublishRelay does not replay its latest value.

With this in mind, it makes sens for a BehaviorRelay to be transformable to Driver, as a driver drives the application using State. The sharing strategy for BehaviorRelay and Driver is to share side effects and replay the latest value while at least one observable is connected.

A PublishRelay is better represented by a Signal, so you probably could use a Signal to emit to. The sharing strategy in this case is will not replay the latest value, but still share the side effects while at least one observable is connected.

(I build this answer using this great comment from @freak4pc on RxSwift's repository)

Grunter answered 29/1, 2019 at 23:36 Comment(1)
Thanks a lot for this comment. You're right. I had missed the part where the Driver was meant to replay the last event ! I makes more sense now :)Elliellicott
B
7

If someone need a simple example:

publishRelay
            .asDriver(onErrorDriveWith: Driver.empty())
            .drive(onNext: { value in

            })
            .disposed(by: disposeBag)
Brann answered 9/4, 2020 at 16:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.