BehaviorSubject vs Observable?

前端 未结 10 2534
迷失自我
迷失自我 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:10

    One thing I don't see in examples is that when you cast BehaviorSubject to Observable via asObservable, it inherits behaviour of returning last value on subscription.

    It's the tricky bit, as often libraries will expose fields as observable (i.e. params in ActivatedRoute in Angular2), but may use Subject or BehaviorSubject behind the scenes. What they use would affect behaviour of subscribing.

    See here http://jsbin.com/ziquxapubo/edit?html,js,console

    let A = new Rx.Subject();
    let B = new Rx.BehaviorSubject(0);
    
    A.next(1);
    B.next(1);
    
    A.asObservable().subscribe(n => console.log('A', n));
    B.asObservable().subscribe(n => console.log('B', n));
    
    A.next(2);
    B.next(2);
    

提交回复
热议问题