Hey, I’ve been stuck in the old school model too. But, I’m starting to think there may be a better way. I’ve written about Redux and NgRX a lot on this blog. I’ve fielded a lot of questions on the Angular slack channel. Most of the questions revolve around the basic question of handling multiple asynchronous calls for data as part of one action. All of the questions presuppose you would need to make each of the calls for data and then use some method of waiting for everything to return and assemble the data before moving on. In each case, I recommend an alternative. What if, each call was a unique action. When each returns, another action is fired that places the return data in the appropriate store, or sub store. In this model, we don’t care when the data comes back. When it comes back, we deal with it appropriately.
Let’s go with one of the more common examples I see.
I need to make a request for a set of records. Once I have the results, for each record in the result, I need to go get a set of child records. Here is how I would deal with this at a very high level using NgRX. I’m sure this would work for multiple Redux patterns but they may call things by different names.
- Fire an Action that request the main set of records.
- The appropriate Effect responds to the action by making an AJAX call for the data.
- When the AJAX call returns,
- fire an Action that puts the main records in the store.
- for each record in the result fire an Action asking for the child record(s).
- The appropriate Effect(s) responds to the request for child records by making AJAX calls.
- When the data returns fire an Action that places the data in the store.
Since your view is listening for changes on the entities in your store, it will update as the data comes in. Even better if you setup a debounce on your listener, the screen will update only when all of the data has been retrieved.
The key concept here is that we no longer care WHEN something happens. We only care THAT it happens. And rather than trying to setup forkJoins() or some other mechanism to flatten this all out, our code ends up being quite simple. Discrete bits of functionality. And now, all our asynchronous code becomes Reactive code. We no longer need to flatten anything out.
Sadly, on the server side, things aren’t quite so easy. At best we are tied to an implementation Observables and the various methods of combining Observables. But I could also see some kind of client/server implementation that used a framework like SignalR or Socket.io so that as the various Observables complete, the data on the client would get updated. An interesting way to make all of the AJAXy calls rather transparent to the user.
When Windows was first created in ran on single core CPUs. It was essentially single threaded. The way it worked was primarily by putting “events” on a que and then sending the events to the appropriate application that needed to know about them.