In some cases, the RxJs combineLatest pipe needs to be used in tandem with a dynamically changing list of input observables. In this article, we'll outline how to implement this with code implementations. If you are not familiar with RxJs or would like a quick refresher, please visit our introduction to observables with RxJs.
Dynamically Changing CombineLatest Observables
If we held a reference to the list of observables we want combineLatest to combine, we could pass that reference in, then makes changes to the array afterwords, but combineLatest will not react to this change. Therefore, we will need to put the reaction before calling combineLatest. We'll discuss two methods of doing this in the sections below.
Implementation Using SwitchMap
The code below showcases a simple example of this implementation strategy:
Implementation Using a Custom Function
To make our code more declarative and easier to read, we can write a function which encapsulates the switchMap and other concerns discussed above. The TypeScript version below preserves the data types. This also allows us to put any other logic within the function itself, such as adding different pipes to our observables: