BehaviorSubject vs Observable?

前端 未结 10 2551
迷失自我
迷失自我 2020-11-22 02:17

I\'m looking into Angular RxJs patterns and I don\'t understand the difference between a BehaviorSubject and an Observable.

From my underst

10条回答
  •  暖寄归人
    2020-11-22 03:19

    The Observable object represents a push based collection.

    The Observer and Observable interfaces provide a generalized mechanism for push-based notification, also known as the observer design pattern. The Observable object represents the object that sends notifications (the provider); the Observer object represents the class that receives them (the observer).

    The Subject class inherits both Observable and Observer, in the sense that it is both an observer and an observable. You can use a subject to subscribe all the observers, and then subscribe the subject to a backend data source

    var subject = new Rx.Subject();
    
    var subscription = subject.subscribe(
        function (x) { console.log('onNext: ' + x); },
        function (e) { console.log('onError: ' + e.message); },
        function () { console.log('onCompleted'); });
    
    subject.onNext(1);
    // => onNext: 1
    
    subject.onNext(2);
    // => onNext: 2
    
    subject.onCompleted();
    // => onCompleted
    
    subscription.dispose();
    

    More on https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/subjects.md

提交回复
热议问题