BehaviorSubject vs Observable?

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

    BehaviorSubject

    The BehaviorSubject builds on top of the same functionality as our ReplaySubject, subject like, hot, and replays previous value.

    The BehaviorSubject adds one more piece of functionality in that you can give the BehaviorSubject an initial value. Let’s go ahead and take a look at that code

    import { ReplaySubject } from 'rxjs';
    
    const behaviorSubject = new BehaviorSubject(
      'hello initial value from BehaviorSubject'
    );
    
    behaviorSubject.subscribe(v => console.log(v));
    
    behaviorSubject.next('hello again from BehaviorSubject');
    

    Observables

    To get started we are going to look at the minimal API to create a regular Observable. There are a couple of ways to create an Observable. The way we will create our Observable is by instantiating the class. Other operators can simplify this, but we will want to compare the instantiation step to our different Observable types

    import { Observable } from 'rxjs';
    
    const observable = new Observable(observer => {
      setTimeout(() => observer.next('hello from Observable!'), 1000);
    });
    
    observable.subscribe(v => console.log(v));
    

提交回复
热议问题