0
0

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 1 year has passed since last update.

【RxSwift】BehaviorRelayとPublishRelay

Last updated at Posted at 2023-10-31

目次

1.BehaviorRelayとPublishRelayの特徴
2.実例
3.おわりに

1. BehaviorRelayとPublishRelayの特徴

  • BehaviorRelayとPublishRelaは.nextメソッドのみ流せる
  • .errorと.completedが流れない
  • .nextメソッドを流すには.accept()を使用する

2. BehaviorRelayとPublishRelayの違い

BehaviorRelay PublishRelay
初期値の有無
valueプロパティの有無
現在値流しの有無
behaviorRelay基本形
var disposeBag = DisposeBag()
let behaviorRelay = BehaviorRelay<Int>(value: 1)

behaviorRelay.subscribe { event in
    print(event)
}.disposed(by: disposeBag)

behaviorRelay.accept(2)
bahaviorRelay.accept(3)

// 実行結果
// next(1)
// next(2)
// next(3)
PublishRelay基本形
var disposeBag = DisposeBag()
let behaviorRelay = PublishRelay<Int>()

behaviorRelay.subscribe { event in
    print(event)
}.disposed(by: disposeBag)

behaviorRelay.accept(2)
bahaviorRelay.accept(3)

// 実行結果
// next(2)
// next(3)

補足:現在値流しの有無

現在値流し
var disposeBag = DisposeBag()
let behaviorRelay = BehaviorRelay<Int>(value: 1)

behaviorRelay.subscribe { event in
    print(event)
}.disposed(by: disposeBag
// ここまで書いただけで初期値value=1が流れる
// 実行結果
// behaviorRelay next(1)

3. おわりに

本記事を最後まで読んでいただきありがとうございました!
RxSwift、combine、SwiftUIなど目まぐるしく変わるiOSのトレンドですが、頑張って食らいつきましょ

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?