RxSwift文档翻译2--Working with Subjects

0 前言

第二节开头的时候稳定顶一个协议扩展和一个方法,便于本章中方法的测试

  • 协议扩展是给每个观察者加一个id的标示符并且打印事件相关的信息

  • 方法的大致作用是将观察序列作为参数传入,然后订阅此序列

extension ObservableType {
    
    /**
     Add observer with `id` and print each emitted event.
     - parameter id: an identifier for the subscription.
     */
    func addObserver(_ id: String) -> Disposable {
        return subscribe { print("Subscription:", id, "Event:", $0) }
    }
    
}

func writeSequenceToConsole<O: ObservableType>(name: String, sequence: O) -> Disposable {
    return sequence.subscribe { event in
        print("Subscription: \(name), event: \(event)")
    }
}

接下来进行本章的翻译

Working with Subjects

  • subject介绍

subject 在Rx的某些实现中充当的是桥梁或代理,它既充当观察者又充当被观察者。 因为它是一个观察者,它可以订阅一个或多个观察器,又因为是被观察者,所以它可以通过重新发出它们观察到的项目,并且它也可以发射新的项目。

  • PublishSubject
    向所有的观察者发送新事件,这些事件是观察者订阅之后的事件,订阅之前的事件,观察者无法接收到
example("PublishSubject") {
    let disposeBag = DisposeBag()
    let subject = PublishSubject<String>()
    
    subject.addObserver("1").disposed(by: disposeBag)
    subject.onNext("🐶")
    subject.onNext("🐱")
    
    subject.addObserver("2").disposed(by: disposeBag)
    subject.onNext("🅰️")
    subject.onNext("🅱️")
}

// 控制台打印的结果:
--- PublishSubject example ---
Subscription: 1 Event: next(🐶)
Subscription: 1 Event: next(🐱)
Subscription: 1 Event: next(🅰️)
Subscription: 2 Event: next(🅰️)
Subscription: 1 Event: next(🅱️)
Subscription: 2 Event: next(🅱️)

其中onNext(:) 方法等同于on(.next(:)方法, 作用是为向订阅者发送Next 事件

  • ReplaySubject
    在新的订阅者订阅的时候会补发事件,bufferSize决定补发事件的数量,如果bufferSize为1则补发一个事件,为2则补发两个
    观察一下bufferSize为1和2不同的值的时候控制台打印的不同情况
example("ReplaySubject") {
            let disposeBag = DisposeBag()
            let subject = ReplaySubject<String>.create(bufferSize: 1)
            
            subject.addObserver("1").disposed(by: disposeBag)
            subject.onNext("🐶")
            subject.onNext("🐱")
            
            subject.addObserver("2").disposed(by: disposeBag)
            subject.onNext("🅰️")
            subject.onNext("🅱️")
        }
// bufferSize = 1
// 控制台打印的结果:
--- ReplaySubject example ---
Subscription: 1 Event: next(🐶)
Subscription: 1 Event: next(🐱)
Subscription: 2 Event: next(🐱)
Subscription: 1 Event: next(🅰️)
Subscription: 2 Event: next(🅰️)
Subscription: 1 Event: next(🅱️)
Subscription: 2 Event: next(🅱️)

// bufferSize = 2
// 控制台打印的结果:
--- ReplaySubject example ---
Subscription: 1 Event: next(🐶)
Subscription: 1 Event: next(🐱)
Subscription: 2 Event: next(🐶)
Subscription: 2 Event: next(🐱)
Subscription: 1 Event: next(🅰️)
Subscription: 2 Event: next(🅰️)
Subscription: 1 Event: next(🅱️)
Subscription: 2 Event: next(🅱️)
  • BehaviorSubject
    向新的订阅者补发送新的事件,如果没有新事件就补发默认值,默认值应该是在BehaviorSubject初始化时候创建的
example("BehaviorSubject") {
    let disposeBag = DisposeBag()
    let subject = BehaviorSubject(value: "🔴")
    
    subject.addObserver("1").disposed(by: disposeBag)
    subject.onNext("🐶")
    subject.onNext("🐱")
    
    subject.addObserver("2").disposed(by: disposeBag)
    subject.onNext("🅰️")
    subject.onNext("🅱️")
    
    subject.addObserver("3").disposed(by: disposeBag)
    subject.onNext("🍐")
    subject.onNext("🍊")
}
// 控制台打印的结果:
--- BehaviorSubject example ---
Subscription: 1 Event: next(🔴)
Subscription: 1 Event: next(🐶)
Subscription: 1 Event: next(🐱)
Subscription: 2 Event: next(🐱)
Subscription: 1 Event: next(🅰️)
Subscription: 2 Event: next(🅰️)
Subscription: 1 Event: next(🅱️)
Subscription: 2 Event: next(🅱️)
Subscription: 3 Event: next(🅱️)
Subscription: 1 Event: next(🍐)
Subscription: 2 Event: next(🍐)
Subscription: 3 Event: next(🍐)
Subscription: 1 Event: next(🍊)
Subscription: 2 Event: next(🍊)
Subscription: 3 Event: next(🍊)

PublishSubject, ReplaySubject, and BehaviorSubject这三种的subject在 disposed of. 的时候不需要自动发出Complete 事件,

  • Variable
    Variable是对BehaviorSubject的封装,所以它具向订阅者发送最近的值的功能。它还有保存当前的值得的功能,它不会发出Error事件,但是它会自动发送Complete事件,并在deinit的时候终止
example("Variable") {
    let disposeBag = DisposeBag()
    let variable = Variable("🔴")
    
    variable.asObservable().addObserver("1").disposed(by: disposeBag)
    variable.value = "🐶"
    variable.value = "🐱"
    
    variable.asObservable().addObserver("2").disposed(by: disposeBag)
    variable.value = "🅰️"
    variable.value = "🅱️"
}
// 控制台打印的结果:
--- Variable example ---
Subscription: 1 Event: next(🔴)
Subscription: 1 Event: next(🐶)
Subscription: 1 Event: next(🐱)
Subscription: 2 Event: next(🐱)
Subscription: 1 Event: next(🅰️)
Subscription: 2 Event: next(🅰️)
Subscription: 1 Event: next(🅱️)
Subscription: 2 Event: next(🅱️)
Subscription: 1 Event: completed
Subscription: 2 Event: completed

** Variable 对象调用asObservable() 方法是为了访问其底层的BehaviorSubject序列。 变量没有使用on运算符(例如onNext(_ :)),而是暴露可用于获取当前值的value属性,并设置一个新值。 设置一个新值也会将该值添加到其底层的BehaviorSubject序列中。**

此处对VariableBehaviorSubject 做一下对比 :

        example("Variable") {
            let disposeBag = DisposeBag()
            let variable =  Variable("🔴")
            
            variable.asObservable().addObserver("1").disposed(by: disposeBag)
            variable.value = "🐶"
            variable.value = "🐱"
            
            variable.asObservable().addObserver("2").disposed(by: disposeBag)
            variable.value = "🅰️"
            variable.value = "🅱️"
        }
        
        example("BehaviorSubject") { 
            let disposeBag = DisposeBag()
            let subject = BehaviorSubject(value: "🔴")
            
            subject.addObserver("1").disposed(by: disposeBag)
            subject.onNext("🐶")
            subject.onNext("🐱")
            
            subject.addObserver("2").disposed(by: disposeBag)
            subject.onNext("🅰️")
            subject.onNext("🅱️")

        }

对比打印结果
可以看出Variable会自动发出Complete事件

对比结果

下一篇:RxSwift文档翻译3--Combination Operators

推荐阅读更多精彩内容