RxJs switchMap vs mergeMap - Intro to Flattening Operators (2021)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

I’ve always worked in angular shops but have been using svelte in a side project. Svelte makes rxjs seem barbaric to me. I used to love using rxjs because it seemed so clever but now Angulars entire reactivity model seems severely flawed and inefficient comparatively.

👍︎︎ 1 👤︎︎ u/yrocrepooc 📅︎︎ Oct 13 2021 🗫︎ replies
Captions
hi everyone welcome back my name is mitchumski and in this video we're going to have a look at flattening operators in rxgs namely we're going to have a look at two of them the first one is the merge map former flat map and switch map and we will see what the difference between them and we're going to use similar mental model and analogs from real life like we did it in the previous video by the way you have to check this out first because uh this current video kind of depends on the previous one so in order to better understand what we're talking about it's better to start from the video right there and yeah don't forget to subscribe to my channel and let's get started with some theory okay let's quickly refresh our knowledge about zip operator we learned in the previous video so it combines multiple streams in our case five ingredient streams then it waits until every of them emits a value then it rubs emitted ingredients into one array and such a way we get kind of new the room and i would suggest you to treat this whole process as a one stream and let's call it the room chef stream so we kind of encapsulate all this logic in this single stream and it emits over time some do rooms one by one right would you agree with me that producing the rooms just for fun it is kind of useless thing and we would need to do it only if someone orders it so let's introduce a new stream called to room order and the value which is being emitted inside the stream it's let's say customer yeah and in real life customer goes where he or she goes to the room kiosk to order some so you can treat this kiosk as a merge map or any another flattening operator currently it doesn't really matter because what i would like to show you is how the data flows in these flattening operators but okay then what happens in the kiosk there happens a function which takes my money as an argument and because the room cannot be done immediately because it requires some time to cook right so the function returns me kind of process of cooking and i kind of subscribe to this process and wait until i get my room once it done and in nutshell the similar thing would happen also in the kiosk if it was working as a switch map and you would reasonably ask why do we need both of these operators well it is because they handle differently the concurrency like how to deal in the situation when the first order is still in progress but already second has arrived so how it would happen in the real life if the kiosk was a merge map which is former flat map so i come to the kiosk i give some money and i subscribe to the process of cooking so basically it means that i just staring at the chef's work yeah he's working but here comes another guy and also orders a doom the chef says like sorry bro i am busy currently and merge map imagine merge map it is a manager of this kiosk she calls another chef who in parallel starts starts to work on the order for the second guy and those processes are independent and it is not necessary that streams should be completed in the same order and they started no the order for the second guy can be finished even before the first one and so on and once someone receives their order he or she goes further to have a lunch and there can be many of these you know parallel orders not necessary two of them there can be really a lot of them now how it would work like if the kiosk was the switch map well initially the same story here i go to the kiosk order some on the room jeff starts to work on it then another guy comes he orders as well chef says that bro i'm busy sorry about that and what does in this case our kiosk manager which is switch map she says to the first chef like you know stop everything you are working on currently do not even finish this order and just go home think i don't know about your productivity and in place of the first chef starts working the second one who works on the order for the second customer and for the first one for the first customer well it was a bad day for him so he didn't get his order unfortunately so this is how it would work in the real life and now let's try to reflect this everything in the code all right welcome to practice session we're going to implement stuff from slides but before we start let's very very quickly recall what we did in the previous video and in the previous video we created uh the angular application which consists just from those five buttons every button represents a separate stream of ingredients and if we click on every of this button it emits the value and once we emit value for every of these five streams zip operator kind of combines values from those streams together and emits array of those values yeah and if i click add cabbage we can see this array right here so this is very simple and this is the code of it so basically what is important those are five buttons and when we click on every of it it emits some value to appropriate stream so here you can see five of them and there below we have durum stream uh carries the zip operator which combines those five uh let's name it sub streams here streams of ingredients together and then it emits the array and we console log it right here simple simple now we have to implement um additional a couple of things and i would start with the orders so we have to create some order stream right so let's do it right here it's going to be a new subject and here i define the type of data which i'm going to dispatch in this stream and it's going to be order or there and i will create the interface for it right next to type the room so and inside order we will have two properties the first is amount which is number so we have to know how many rooms has been ordered and we have to know the customer id which is also the number and you will see why do we needed everything it just to you know visualize stuff so uh we have this order and we would need uh some also delivery stream yeah where we will uh dispatching uh already finished order so i will create it next to the room and we'll name it like delivery stream yeah and it's going to be also observable of type product i will name it like this so product this is another interface which has property product which is our do room actually right and we would like to know to which customer we want to deliver so again we have to know customer id all right so looks pretty good and here below next to the room i would suggest you to start the delivery stream so we'll say the delivery it starts and it starts from what it starts from our order right so i say that it starts from order and then we call the pipe method so now we have we started our delivery order and inside first of all let's maybe lock that that we know that some order has been arrived so i will use stop operator right here and we get the order and i'm going to just console log it so here we go yeah once we dispatch something we see that new order has been arrived that's fine now we have to like once we get the order we have to start uh cook the room right so this is where we're going to merge our the room stream into our delivery stream and as we know in order to merge two streams we have to use some flattening operator and let's start with the flat map which is renamed to merge map this operator as you know it takes a function and a function gets a couple of arguments and the first one is our order so let's place it here and we should return the kind of process of creating the room so basically we have to return the stream of the room like this yeah and then kind of we subscribe to merge mob will subscribe to the room stream yeah under the hood and it will be waiting until the room emits some valley and once it meets the value then merge map casts this value downstream to next operators which come after the merge map so in our case it could be i don't know any operator but i would use another tab and i would just console log the product here i will be there will be already prepared product right so i will console log it as well here we go delivered product fine however you see the typescript complaints it says that observable of either the room or product it's not assignable to type observable of product and indeed because from the room we return not a product we return that room so we have to somehow you know uh transform it yeah first of all let's probably uh destructure our order and get amount and customer id then because i want to further like transform data from the room i want to open another pipe yeah you can do it why not and there inside and i'm going to say that please take take only amount of two rooms has been ordered if we ordered only to the rooms within this stream should be produced only two of them yeah we don't need more and once two uh the rooms like arrived then stream kind of completes okay after the take we can use map operator in order to transform because this observable which expects that there will be a product and currently we get only the room here but we have to return the object which is a product to room and customer id is our customer id from here so we basically can leave it as it is so here we go yeah it looks way more better with uh this formatting so what we have done we just say durum stream that okay you have limitation of amount of amount and then once you like produ before you produce before you cast it downstream to main delivery stream please format and uh create the object with the product and customer id i hope it's pretty much clear so now our stream more or less done the only one missing thing is that we have to dispatch something inside the order right so we have to create something like button once we click we dispatch some order right so i would suggest you to create it somewhere right here button where i click i will call function dispatch order and here order and then we have to create this method i will create it somewhere right here and i will add some code and quickly explain you what it does so here i just randomly generate the amount of uh ordered rooms here and then i increment customer id kind of yeah like to see that next order belongs to next customer and then i dispatched the amount and customer id right here and i created the separate um global variable customer id right here yeah all right i think we're almost done the one thing maybe let's um visually separate our order doom button from ingredients buttons kind of to visually see that it's different stuff and we have to yeah we have to subscribe not to the do room right here but we have to subscribe now to the delivery i believe yeah so delivery will say that this is not the room this is the product and this product has value product and basically we don't need this check anymore and here i should say that this is going to be product yeah hey we are done so we can test it out and what is first interesting thing is that now if i click on these buttons nothing like happens yeah you remember before we emitted some values why it happened so well if you remember i told you that merge map under the hood subscribes to the observable which we return from this function so to our room stream but we didn't dispatch yet any value into this stream so we didn't even reach this part in order to subscribe to our doom stream and activate it that's why and and you know that observables they are lazy they are like start execution only when you subscribe to it and because we didn't reach this part and we didn't subscribe to it it is like the stream is not created yet yeah in order to activate it we have to emit vale into the order so we have to click the order the room button first so now i ordered the room you can see that like we ordered amount one so one drum for customer with id one it means that we reached this part we activated kind of merge map merge map subscribed to dorome stream and now it waits until the value will be emitted from this doom stream and we know that the room stream if we go a little bit up you can see that this is the zip operator which waits until every of these ingredient streams will emit any value and only then value will be emitted to the durum stream and merge map will then cast this value from durian stream downstream to other operators so now i have to click on all these five buttons in order to like proceed further so i add flat bread and you can see right now the stream is activated so we see those values i click the meat i click the sauce tomato cabbage and boom now you can see enjoy the room this is our console log right here from durum stream and here we have delivered product and we have this product itself and the customer id one so it was delivered to user one now what the interesting as you can see we ordered only one durum right so it means that this stream executed once it emitted one room and it completes it died and if you try to click one more time on these buttons nothing happens because this stream is dead okay now i would like to show you what happened when we have bigger amount and if new customer arrives so i do order so customer id amount to the rooms so we deliver the first one and the first stream like because we wait for two drones the stream which was created for the first order which is right here now stays alive because we emitted only one and we want to take two values from it right so it stays alive then imagine the new customer arrives so customer two he ordered three rooms yeah now if we try to click on those five that will be delivered product for customer one and for customer two but for customer one the stream already completed because we emitted two of them so currently when i click one more time we have only one stream remaining inside the merge map yeah because it's scheduled another stream for second user and indeed when we click on it it was created the second one but this stream waits for the third one before to complete so we have to produce the third one done third second stream that as well and we have no streams inside the merge map currently so i click nothing happens yeah what happens if we change merge map with switch map in this case imagine i like schedule a new order uh there is amount of 3d rooms should be created we create first one yeah but we are not finished creating the first um the room yeah but imagine that already the second order uh comes to us yeah so you can see new order right here what happens right here is that this stream which was scheduled for the first order is cancelled and that it doesn't exist anymore and it was replaced with the new stream which was scheduled for the second order so if i currently create new um to do you can see that it belongs to the customer too so to the latest one so this is the whole difference between uh flat map and switch map when flat map creates you know many uh sub streams and switch map keeps only one active stream and if something some new order arrives it kills the current active stream and schedules the new one in real life you could benefit from switch map when you do http calls yeah this is very kind of famous use case for it when you when you have some active http call and then arrives the request for another one you will probably want to cancel the previous one which is uh activity and not completed yet you would like to complete it and uh schedule the new request in order to get latest of valium flatmap you could use if you have example you know some logger which sends frequently requests to the server and all of these requests should be saved yeah and they should not be cancelled in this case like you can use flat map if you care about this this is where you could use these operators in a real live applications all right guys thanks for watching i hope you enjoyed this video and don't forget to check out my video courses the first one is about advanced angular material theming and the second one about graphql engine called hasura which allows you to turn your relation database mysql or postgresql into real life graphql endpoints really cool courses it is worth to check this out links will be in the video description and of course i'm waiting for your comments and feedbacks right there in the comment sections and please if you like this video share it with your colleagues and friends that's it i wish you a productive week ahead stay safe and see you in the future videos you
Info
Channel: Decoded Frontend
Views: 3,897
Rating: undefined out of 5
Keywords: rxjs switchmap vs mergemap, rxjs mergemap vs switchmap vs concatmap, rxjs switchmap, rxjs flatmap, rxjs mergemap, rxjs, rxjs operators, rxjs angular, angular, angular tutorial, Angular 12
Id: qYdKmYp95Jg
Channel Id: undefined
Length: 25min 43sec (1543 seconds)
Published: Tue Oct 12 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.