BehaviorSubject vs Observable?

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

    Think of Observables as a pipe with flowing water in it, sometimes water flows and sometimes it doesn't. In some cases, you may actually need a pipe that has always water in it, you can do this by creating a special pipe which always contains a water no matter how small it is, lets call this special pipe BehaviorSubject, if you happens to be a water supply provider in your community, you can sleep peacefully at night knowing that your newly installed pipe just works.

    In technical terms: you may encounter usescases where an Observable should always have value in it, perhaps you want to capture the value of a input text over time, you can then create an instance of BehaviorSubject to ensure this kind of behavior, lets say:

    
    const firstNameChanges = new BehaviorSubject("");
    
    // pass value changes.
    firstNameChanges.next("Jon");
    firstNameChanges.next("Arya");
    
    

    You can then use "value" to sample changes over time.

    
    firstNameChanges.value;
    
    

    This comes handy when you combine Observables later, by taking a look at the type of your stream as BehaviorSubject you can then ensure that the stream at least fires or signal just once atleast.

提交回复
热议问题