Subjects的使用

什么是Subjects

Subjet是observable和Observer之间的桥梁,一个Subject既是一个Obserable也是一个Observer,他既可以发出事件,也可以监听事件。

PublishSubject

当你订阅PublishSubject的时候,你只能接收到订阅他之后发生的事件。subject.onNext()发出onNext事件,对应的还有onError()和onCompleted()事件

let disposeBag = DisposeBag()
let publishSubject = PublishSubject()
        
        publishSubject.subscribe { (event) in
            print(event)
        }.disposed(by: disposeBag)
        
        publishSubject.onNext("1")
        publishSubject.onNext("2")
        publishSubject.onNext("3")
        publishSubject.onCompleted()
next(1)
next(2)
next(3)
completed

ReplaySubject

当你订阅ReplaySubject的时候,你可以接收到订阅他之后的事件,但也可以接受订阅他之前发出的事件,接受几个事件取决与bufferSize的大小

let disposeBag = DisposeBag()
let replaySubject = ReplaySubject.create(bufferSize: 2)
        replaySubject.onNext("a")
        replaySubject.onNext("b")
       replaySubject.onNext("c")
        replaySubject subscribe { (event) in
            print(event)
        }.disposed(by: disposeBag)
        
        replaySubject.onNext("1")
        replaySubject.onNext("2")
        replaySubject.onNext("3")
        replaySubject.onCompleted()
next(b)
next(c)
next(1)
next(2)
next(3)
completed

BehaviorSubject

当你订阅了BehaviorSubject,你会接受到订阅之前的最后一个事件。

let disposeBag = DisposeBag()
let behaviorSubject = BehaviorSubject(value: "abc")
        behaviorSubject.onNext("a")
        behaviorSubject.onNext("b")
        behaviorSubject.onNext("c")
        behaviorSubject.subscribe { (event) in
            print(event)
        }.disposed(by: disposeBag)
        
        behaviorSubject.onNext("1")
        behaviorSubject.onNext("2")
        behaviorSubject.onNext("3")
        behaviorSubject.onCompleted()
next(c)
next(1)
next(2)
next(3)
completed

Variable

Variable是BehaviorSubject一个包装箱,就像是一个箱子一样,使用的时候需要调用asObservable()拆箱,里面的value是一个BehaviorSubject,他不会发出error事件,但是会自动发出completed事件。

let disposeBag = DisposeBag()
let variable = Variable("abc")
        variable.value = "1"
        variable.value = "2"
        variable.asObservable().subscribe { (evevt) in
            print(evevt)
        }.disposed(by: disposeBag)
        variable.value = "a"
        variable.value = "b"
        variable.value = "c"
next(2)
next(a)
next(b)
next(c)
completed

你可能感兴趣的:(Subjects的使用)