Thursday, April 5, 2018

long lasting subscriptions with NgRx?

Observables can listen to a web socket right? This is how the long life thing was original explained to me and before my immediate role I would have rolled my eyes and said: "When will I ever talk to one of those?" as in just speaking to an API endpoint the only things I need to do with Observables are things I can just do with promises anyways, right? An API endpoint is not going to tell you something twice so why would you ever do a .subscribe when one can just to a .toPromise().then instead? All I ever interact with is REST APIs. I've never worked anywhere where they have web sockets going on and I still don't. However we are using the Redux store and there are times when data changes in long life. Imagine:

  1. In spinning up an app we call an API endpoint to get all of our Cats.
  2. Before the promise from the API comes back we are hitting ngOnInit in outermost component in our Russian Doll hierarchy, a smart component, and also the constructor where a resolver is handing in the data context for the store. In ngOnInit we map off a Cats variable, but at this moment in time there are no Cats!
  3. We hand a Cats | async onto the first dumb component nested in our smart component.
  4. We display Cats[0]?numberOfLives in the template, but at first this gives us nothing.
  5. The API promise comes back.
  6. The store gets updated with thirteen beautiful Cats.
  7. Change detection triggers the subscription in Cats back at the smart component to update that which the Observable wraps, the meat of data.
  8. Change detections hands Cats down the Russian Doll chain.
  9. At the template of the component that is one component deep we see the number 9.

As we do CRUD operations to the Cats and go the API and back the store similarly updates. The use of the async pipe to hand a subscription's sweet stuff on to a second component is a pretty good pattern herein. The async pipe and doing a .subscribe off of params in the routing paradigm are, I think, the only two examples of .subscribe that will clean then themselves up when unused without creating a memory leak or causing you to explicitly destroy them with an .unsubscribe at an ngOnDestroy.

 
 

Addendum 9/17/2019: Here I uncover a third scenario in which you do not have to unsubscribe to a subscription.

No comments:

Post a Comment