Tutorial hero
Lesson icon

View Model Streams

Originally published July 28, 2022 Time 3 mins

Since we are on the topic of reactive programming and RxJS this week, I thought it would be fitting to make the tip about creating view models with observable streams.

If you have been watching/reading my tutorials, this is a technique you might have noticed me using:

vm$ stream that contains all values

The idea is simple enough: take all of the streams you want to display in your template and chuck them inside of a combineLatest to create a single new vm$ stream that contains all of the values you need for the template:

vm template

Also notice that I map the observable to convert the array of values into an object so that I can easily reference the values by their name rather than by an index.

Even if you had some static/non-stream value you wanted to include in the vm you could still include it just by creating a stream of that value, e.g:

static/non-stream value

This isn’t really required, you could just bind to that value directly in the template, but for consistency sake you might want to have all values displayed in the template accessed through the single vm object.

There are factors to consider here, so it’s not just as simple as throwing everything inside of combineLatest.

Let’s say that some of the values you need from streams are not synchronous, that is to say that the observable stream won’t emit a value immediately - perhaps you are fetching data with an HTTP request.

If you are using combineLatest, then it will not emit until all the input streams have emitted a value. This means that all of your other values are going to be held up whilst you wait for that request to finish, which in most cases probably isn’t what you want.

One way to work around this would be to use the startWith operator to give the stream you are waiting on an initial value of null:

startWith operator

But just keep in mind that this means you now need to explicitly handle that null value in your template. How exactly you handle this really depends on the situation - I just wanted to add this section at the end here to not make this vm/combineLatest approach seem more simple than it is.

All that said, for situations where I have more than a couple of streams to display in the template, I love this approach for keeping things simple and reducing the number of times I need to use the async pipe.

Learn to build modern Angular apps with my course