What is the difference between a Observable and a Subject in rxjs?

前端 未结 8 1058
难免孤独
难免孤独 2020-12-01 00:05

i was going through this blog and to read about Observables and i couldnt figure out the difference between the Observable and a Subject

8条回答
  •  借酒劲吻你
    2020-12-01 00:47

    Imagine if you have a stream of data coming into your application like in a websocket connection. You want a way to handle it. There is a few solution:

    1. normal ajax request: This solution is not viable because it is not applicable to process push data. It is more of a pull then a push.

    2. Promise: Also not good because you have to trigger them and they can only retrieve once. Also more of a pull then a push.

    So in order to retrieve this data, in the old time, we do a long-polling. Which is where we set an interval function to retrieve that stream of data every 1 minute for an example. Though it works, it actually burdening resources like CPU and memory.

    But now with option no 3,

    3. Observable: You can subscribe and let the stream of data to come in non-stop until the function complete has been called.

    Cool right ? But then there is another problem. What if you want to observe incoming data only once somewhere in your application. But you want to use that data simultaneously around your application when the data arrived. That is when and where you use Subject. You place subject.subscribe() at places you want to use throughout your application. When the data arrived, places where there is subject.subscribe() will process them simultaneously. But the observer must subscribe with the subject as its argument like this.

    observer.subscribe(subject).

    Example application is when you want to build a notification alert.

    You cannot have multiple subscription of the same observable because chances are, each subscribers will received different input data. But with subject, all that subscribe() through subject will be retrieving the same data.

    Another analogy is through magazine subscription. Each subscribers will received the magazine with their name on it. So, different subscription = different receiver name.(Normal Observable) But when you share with your friends, all of your friend would receive the same magazine with only your name on it.(Normal Observable with Subject)

    This guy explain it very well with code example. You can check it out at https://javascript.tutorialhorizon.com/2017/03/23/rxjs-subject-vs-observable/

    Hopefully this answer helps.

提交回复
热议问题