What is the difference between Subject and BehaviorSubject?

后端 未结 5 829
小蘑菇
小蘑菇 2020-11-22 04:53

I\'m not clear on the difference between a Subject and a BehaviorSubject. Is it just that a BehaviorSubject has the getValue()

5条回答
  •  孤街浪徒
    2020-11-22 05:11

    It might help you to understand.

    import * as Rx from 'rxjs';
    
    const subject1 = new Rx.Subject();
    subject1.next(1);
    subject1.subscribe(x => console.log(x)); // will print nothing -> because we subscribed after the emission and it does not hold the value.
    
    const subject2 = new Rx.Subject();
    subject2.subscribe(x => console.log(x)); // print 1 -> because the emission happend after the subscription.
    subject2.next(1);
    
    const behavSubject1 = new Rx.BehaviorSubject(1);
    behavSubject1.next(2);
    behavSubject1.subscribe(x => console.log(x)); // print 2 -> because it holds the value.
    
    const behavSubject2 = new Rx.BehaviorSubject(1);
    behavSubject2.subscribe(x => console.log('val:', x)); // print 1 -> default value
    behavSubject2.next(2) // just because of next emission will print 2 
    

提交回复
热议问题