This lesson will highlight the true purpose of the zip operator, and how uncommon its use cases are. In its place, we will learn how to use the combineLatest operator.
[00:00] Sometimes in our Ext JS, we need to wait until many observables have emitted a value, to then combine those values together. This is a common use case with promises. Actually, there is a method called promise.all, which I hope is familiar to you.
[00:15] Often, we need a similar functionality to promise.all, but in our Ext JS. For instance, imagine that we're calculating the volume of a room from its components like length, width, and height.
[00:26] We have these observables to represent those, and then maybe you have used zip for this purpose. Now zip will actually work in this case, it takes the member observables like these three observables and then it also takes a function which tells how do we combine those three values into one single value.
[00:49] In this case, we'll actually produce the correct volume there, but with a detail that if we would have updated the width and only the width to be eight meters, for instance, then we wouldn't see 5x7x2.8 and also then 5x8x2.8, we only saw 5x7x2.8.
[01:09] It didn't actually consider this value, and that's because of the way that zip works, it's basically waiting for the second value from all of these other observables, so we need to add also here six, and still it's not enough because it's waiting for the second value from this observable, so we also need to add that value there.
[01:32] Now, if we run this, it will calculate the volume for the first of these values, and also for the second of these values.
[01:41] As you see, zip works in this synchronized manner because it's going to calculate for the first of these, and second of these, and third of these, and it's not going to mix the first with the second, and that type of stuff. Actually, this is probably not what you wanted. Zip is very specific, but a better operator to use by default is combineLatest, which has a similar signature to zip.
[02:11] We don't need to change anything here, and then combineLatest allows us to update only one of these values and then as you see, it will calculate 5x7x2.8 which gives us 98, and also 5x7x2.5 which gives us 87.5.
[02:29] That's why it's called combineLatest, because it only combines the latest values from each of these member observables. Basically, only the most recently emitted values from each of these members.
[02:43] The lesson here is when you're combining many observables together to produce one value, then use combineLatest by default. Only use zip when you know that the observables being combined are guaranteed to have synchronized emissions which is quite rare, to be frank.