亲宝软件园·资讯

展开

RxSwift Subjects RxSwift发送及订阅 Subjects、Variables代码示例

芬达 人气:0

Subjects 介绍

1. Subjects 是订阅者,也是Observable

订阅者:它能动态的接收新的值。

Observable: 当Subjects有了新值后会通过Event将新值发出给他的所有订阅者。

2. 常用的方法

3. Subjects 有四种PublishSubject、BehaviorSubject、ReplaySubject、Variable

相同点

不同点

let sub = PublishSubject<String>()

sub.onNext("订阅之前的不能接收到")

sub.subscribe { event in
  print(event.element)
//Optional("订阅之后的可以接收到")
//nil
}.disposed(by: disposeBag)

sub.onNext("订阅之后的可以接收到")
//结束
sub.onCompleted()
/// 结束之后添加的订阅能收到 completed
sub.subscribe { event in
  print(event)
}
sub.onNext("结束后发的都收不到")

BehaviorSubject

需要一个默认值初始化

当一个订阅者订阅之后会立马收到上一个Event,之后就是正常情况发一个收一个。

onCompleted()之后的订阅者也只能收到Completed。

let sub = BehaviorSubject(value: "默认值")

sub.subscribe { event in
  print("订阅1", event)
}.disposed(by: disposeBag)
sub.onNext("发送1")
sub.subscribe { event in
  print("订阅2", event)
}.disposed(by: disposeBag)
sub.onCompleted()
sub.subscribe { event in
  print("订阅3", event)
}.disposed(by: disposeBag)

订阅1 next(默认值)
订阅1 next(发送1)
订阅2 next(发送1)
订阅1 completed
订阅2 completed
订阅3 completed

ReplaySubject

创建的时候需要一个参数bufferSize设置记录个数

新添加的订阅会接收到之前发送的两个 Event,如果不足两个就只接收一个。

如果超过两个只接收最新的两个。

如果订阅时已经结束除了会接收到最新的两个Event外还有结束的complete或error。

let sub = ReplaySubject<String>.create(bufferSize: 2)

sub.subscribe { event in
  print("订阅1", event)
}.disposed(by: disposeBag)
sub.onNext("发送1")
print("-------")
sub.subscribe { event in
  print("订阅2", event)
}.disposed(by: disposeBag)

sub.onNext("发送2")
sub.onNext("发送3")
sub.onNext("发送4")
print("-------")
sub.subscribe { event in
  print("订阅3", event)
}.disposed(by: disposeBag)
sub.onCompleted()
print("-------")
/// 不仅会收到最后的两个 event 还有 Completed
sub.subscribe { event in
  print("订阅4", event)
}

订阅1 next(发送1)
-------
订阅2 next(发送1)
订阅1 next(发送2)
订阅2 next(发送2)
订阅1 next(发送3)
订阅2 next(发送3)
订阅1 next(发送4)
订阅2 next(发送4)
-------
订阅3 next(发送3)
订阅3 next(发送4)
订阅1 completed
订阅2 completed
订阅3 completed
-------
订阅4 next(发送3)
订阅4 next(发送4)
订阅4 completed

BehaviorRelay

基本同 BehaviorSubject功能一样,但是不能主动调用onCompleted和error,会在BehaviorRelay释放前调用

let sub = BehaviorRelay(value: "初始值")

sub.subscribe { event in
  print("第一次订阅", event)
}.disposed(by: disposeBag)
sub.accept("新值1")
sub.subscribe { event in
  print("第二次订阅", event)
}.disposed(by: disposeBag)

加载全部内容

相关教程
猜你喜欢
用户评论