2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RxSwift(RxCocoa)のBehaviorRelayとPublishRelayについて

Posted at

はじめに

私事ですが現在個人開発を進めていまして、その中でRxSwiftを積極的に採用しています。
RxSwift自体はだいぶ触っていなかったので、過去を思い出しつつ少しまとめの記事を書こうと思います。

Relayとは

さて、Rxswiftではデータバインディングのために手段としてRelayというものがあります。
これはObservableの一種で、.nextだけ流すことができます。
.nextイベントを流すためにはacceptメソッドを使います。
言い換えると.errorや.completedは流れることはないということです。
(.errorや.completedを流したいのであればSubjectを使います。)

具体的には以下の二つあります。

BehaviorRelay
PublishRelay

VariableはRxSwift4.0.0からBehaviorRelayに代替する形で廃止されました。

Relayの使い道

UIとモデルをバインドして変化を伝えたい時

両者の違い

BehaviorRelay

let behaviorRelay = BehaviorRelay<String>(value: a)
 
behaviorRelay.subscribe { event in
    print(event)
}.disposed(by: disposeBag)
 
behaviorRelay.accept(b)
behaviorRelay.accept(c)
behaviorRelay.accept(d)
 
// 実行結果
// next(a)
// next(b)
// next(c)
// next(d)

PublishRelay


let publishRelay = PublishRelay<String>()
 
publishRelay.subscribe { event in
    print(event)
}.disposed(by: disposeBag)
 
publishRelay.accept(a)
publishRelay.accept(b)
publishRelay.accept(c)
 
// 実行結果
// next(a)
// next(b)
// next(c)

両者の違いを以下にまとめました。

BehaviorRelay PublishRelay
.next
初期値
value
現在値を流すか

特に大きな違いは値を保持するかしないかの違いと言えます。
BehaviorRelayの方はsubscribeやbindした時に現在値が流れるのでデータを保持したいのであればBehaviorRelay、
そうでなければPublishRelayを使用するのが適切であると思います。

終わりに

本記事は今年最後に執筆にあたるかなと思います。最後まで読んでくださいましてありがとうございました。
来年はさらなる飛躍と成長を実現する一年にしていきたいと思います。

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?