Subject

作者: NextStepPeng | 来源:发表于2018-01-12 16:56 被阅读0次

    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

    相关文章

      网友评论

          本文标题:Subject

          本文链接:https://www.haomeiwen.com/subject/uqbfoxtx.html