Meaning of sharing (replay:1) in BehaviorRelay

Asked 2 years ago, Updated 2 years ago, 90 views

You may see share(replay:1) using BehaviorRelay on RxSwift.

let relay=RxCocoa.BehaviorRelay<String>(value:"")
variable:RxSwift.Observable<String>{
    return relay
        .observeOn(MainScheduler.instance)
        .share(replay:1)
        // ↑ Here
}

I think BehaviorRelay will return the current value when subscribed, but what does it mean to write share(replay:1)?

Reference
[RxSwift] I summarized Behavior Relay and Publish Relay

swift ios rx-swift

2022-09-29 21:48

1 Answers

I've been using Rx for years, but I've never seen a code with .share(replay:1) on Behavior Relay🤔

.share(replay:1) is used for hot conversion (basically), but it doesn't make sense because the Behavior Relay just before is hot...

However, as the comment says, if

variable:RxSwift.Observable<String>{
    return relay
        .map {$0.uppercased()}
        .share(replay:1)

If there is an operator who converts to cold just before, even if you subscribe only once, it will be meaningful considering the future!


2022-09-29 21:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.