Search code examples
angularrxjsobservablesubject-observer

RxJS & Angular 6 - observables, subjects and basic get and add operations on arrays


I'm struggling to wrap my head around observables/observers/subjects and angular. I've looked through a number of tutorials covering observable basics and the basic subscription scenario makes sense. These tutorials do not seem to cover adding to observable collections however. Most of them also seem to focus on using the HttpClient, whereas I am trying to mock up some data without relying on a web service - just a basic in-memory array of objects for testing.

I've created a simple application to showcase my confusion.

Component 1 and Service 1 showcase a basic non-observable way of getting a collection of numbers and adding new numbers. Component 2 and Service 2 showcase a somewhat observable way of getting data and automatically getting updates due to subscription. I am using a Subject to do that.

https://github.com/rpasechnikov/observable-test-app

Would anyone be able to point out whether I am on the correct path or am I completely misunderstanding the observable pattern? Do I need to use a Subject here or should I be able to stick to Observables? If so - how do I raise a next() notification from that? On top of that, does anyone have any ideas on why is the first this.subject.next() not trigger an update, whereas further calls do?

Thanks heaps!!


Solution

  • The concept of using Observables can be easily misunderstood since there are many things to look at all at once!!!

    However you should not be alarmed as they aren't as bad as you might expect.

    You are using a special type of Observable one that is both an Observer and an Observable amongst other things such as multicasting.

    Observer: You use me when you want to update the observable stream via next

    Observable: You use me when you want to get values from the observable stream via subscribe

    Ben Lesh gave a talk on Subjects

    In your case (Service 2 on your github) you are using a Subject. Which means if I have no observers (someone has subscribed to me) to before my stream is updated via next that person will not get the value.

    You can try to use a BehaviorSubject. Which the main difference is

    1. I must have an initial Value
    2. Whenever someone subscribes to me they will always get the latest value regardless if it before or after i am updated.

    Give it a try!

    Hope this helps