Subject

2018-01-12  本文已影响0人  NextStepPeng

PublishSubject 是Observable的子类

var publishSubject = PublishSubject()

        publishSubject.onNext("Hello")

        publishSubject.onNext("Hello1")

        let publishSubscription = publishSubject.subscribe(onNext: { (str) in

            print("str\(str)")

        })

        publishSubject.onNext("Hello2")

        let publishSubscription2 = publishSubject.subscribe(onNext: { (str) in

            print("str2\(str)")

        })

        publishSubject.onNext("Hello3")

打印:

strHello2

strHello3

str2Hello3

结论:PublishSubject 只能受(只能接受订阅之后发送的代码)

BehaviorSubject  可以介绍上一个加后面所有,所以的构造方法是BehaviorSubject(value: "Value A")

let behaviorSubject = BehaviorSubject(value: "Value A")

        behaviorSubject.onNext("Value A1")

        behaviorSubject.onNext("Value A2")

        behaviorSubject.subscribe( onNext:{

            print("订阅者1:\($0)")

        })

        behaviorSubject.onNext("Value B")

        behaviorSubject.onNext("Value C")

        let  behaviorSubjectTwo = behaviorSubject.subscribe( onNext:{

            print("订阅者2:\($0)")

        })

        behaviorSubject.onNext("Value D")

        behaviorSubject.onNext("Value E")

打印

订阅者1:Value A2

订阅者1:Value B

订阅者1:Value C

订阅者2:Value C

订阅者1:Value D

订阅者2:Value D

订阅者1:Value E

订阅者2:Value E

上一篇下一篇

猜你喜欢

热点阅读