RxSwift概念解惑一

本系列文章将对RxSwift中一些比较容易混淆的概念和操作进行详细的讲解

PublishSubject vs ReplaySubject vs BehaviorSubject vs Variable

PublishSubject

时序图

PublishSubject

示例代码

example("PublishSubject") {
    let disposeBag = DisposeBag()
    let subject = PublishSubject<String>()
    
    subject.addObserver("1").addDisposableTo(disposeBag)
    subject.onNext("🐶")
    subject.onNext("🐱")
    
    subject.addObserver("2").addDisposableTo(disposeBag)
    subject.onNext("🅰️")
    subject.onNext("🅱️")
}

运行结果

Subscription: 1 Event: Next(🐶)
Subscription: 1 Event: Next(🐱)
Subscription: 1 Event: Next(🅰️)
Subscription: 2 Event: Next(🅰️)
Subscription: 1 Event: Next(🅱️)
Subscription: 2 Event: Next(🅱️)

ReplaySubject

ReplaySubject

示例代码

example("ReplaySubject") {
    let disposeBag = DisposeBag()
    let subject = ReplaySubject<String>.create(bufferSize: 3)
    
    subject.addObserver("1").addDisposableTo(disposeBag)
    subject.onNext("🐶")
    subject.onNext("🐱")
    
    subject.addObserver("2").addDisposableTo(disposeBag)
    subject.onNext("🅰️")
    subject.onNext("🅱️")
}

运行结果

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").addDisposableTo(disposeBag)
    subject.onNext("🐶")
    subject.onNext("🐱")
    
    subject.addObserver("2").addDisposableTo(disposeBag)
    subject.onNext("🅰️")
    subject.onNext("🅱️")
    
    subject.addObserver("3").addDisposableTo(disposeBag)
    subject.onNext("🍐")
    subject.onNext("🍊")
}

运行结果

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(🍊)

Variable

示例代码

example("Variable") {
    let disposeBag = DisposeBag()
    let variable = Variable("🔴")
    
    variable.asObservable().addObserver("1").addDisposableTo(disposeBag)
    variable.value = "🐶"
    variable.value = "🐱"
    
    variable.asObservable().addObserver("2").addDisposableTo(disposeBag)
    variable.value = "🅰️"
    variable.value = "🅱️"
}

运行结果

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

Updated:

Comments