{"id":2358,"date":"2022-11-09T23:32:50","date_gmt":"2022-11-09T22:32:50","guid":{"rendered":"https:\/\/nguenkam.com\/blog\/?p=2358"},"modified":"2022-11-09T23:32:50","modified_gmt":"2022-11-09T22:32:50","slug":"rxjs-forkjoin-vs-combinelatest","status":"publish","type":"post","link":"https:\/\/nguenkam.com\/blog\/index.php\/2022\/11\/09\/rxjs-forkjoin-vs-combinelatest\/","title":{"rendered":"RxJS : forkJoin vs combineLatest"},"content":{"rendered":"\n<p>RxJS (Reactive Extensions for JavaScript) is\u00a0<strong>a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code<\/strong>.<\/p>\n\n\n\n<p>This library offers us a lot of operators.One such operators are\u00a0<strong>forkJoin<\/strong>\u00a0and\u00a0<strong>combineLatest<\/strong>.<\/p>\n\n\n\n<h4>forkJoin<\/h4>\n\n\n\n<p><strong><mark>forkJoin<\/mark><\/strong>\u00a0is a special operator from RxJx that let\u2019s you combine \/ accept multiple ObservableInputs and returns the objects of values with exact shape of input.<\/p>\n\n\n\n<p>let us imagine such a situation :  <em>We have a scenario to fetch multiple API\u2019s response and load the data based on all responses.<\/em><\/p>\n\n\n\n<p>one way to solve this  will be by calling all the api\u2019s one by one, like seen below.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  ngOnInit() {\r\n    this.data.getVehicles().subscribe(data => console.log(data));\r\n    this.data.getUsers().subscribe(data => console.log(data));\r\n    this.data.getHackers().subscribe(data => console.log(data));\r\n    this.data.getArticles().subscribe(data => console.log(data));\r\n  }<\/code><\/pre>\n\n\n\n<p><span class=\"has-inline-color has-luminous-vivid-orange-color\"><em>But  how to act now, if certain areas of UI require all the API\u2019s response together?<\/em><\/span><\/p>\n\n\n\n<p>That is where the <strong><em>&#8220;forkJoin<\/em><\/strong>&#8221; operators comes into play : <span class=\"has-inline-color has-vivid-cyan-blue-color\"><strong>forkJoin executes all Observables parallely and completes the execution only if all Observables emit the result.<\/strong><\/span><\/p>\n\n\n\n<p>Even in an unlikely scenario where one of the API is delayed, the forkJoin waits for it to complete.<\/p>\n\n\n\n<p>Our code becomes like this.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>   const observable = forkJoin({\r\n      vehicles: this.data.getVehicles(),\r\n      users: this.data.getUsers(),\r\n      hackers: this.data.getHackers(),\r\n      articles: this.data.getArticles(),\r\n    });\r\n    observable.subscribe({\r\n      next: (value) => console.log(value),\r\n      complete: () => console.log('Completes with Success!'),\r\n    });\n\n\n\/\/ output\r\n\/\/ articles: Array&#91;26]\r\n\/\/ hackers: Array&#91;30]\r\n\/\/ users: Array&#91;10]\r\n\/\/ vehicles: Array&#91;25]\r\n\/\/ Completes with Success!<\/code><\/pre>\n\n\n\n<p>The final response object will have properties that are defined in forkJoin such as\u00a0<mark>vehicles<\/mark>,\u00a0<mark>users<\/mark>,\u00a0<mark>hackers<\/mark>\u00a0and\u00a0<mark>articles<\/mark>.<\/p>\n\n\n\n<p>If any one HTTP call fails, the entire forkJoin mechanism fails and throws an error.<\/p>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h4>combineLatest<\/h4>\n\n\n\n<p><mark><strong>combineLatest<\/strong><\/mark>\u00a0is similar to\u00a0<strong>forkJoin<\/strong>, except that it combines the latest results of all the observables and emits the combined final value. <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const observable = combineLatest({\r\n      vechicles: this.data.getVehicles(),\r\n      users: this.data.getUsers().pipe(delay(2000), startWith(null)), \/\/ Simulate network delay\r\n      hackers: this.data.getHackers(),\r\n      articles: this.data.getArticles().pipe(delay(500), startWith(null)),  \/\/ Simulate network delay\r\n    });\r\n    observable.subscribe({\r\n      next: (value) => console.log(value),\r\n      complete: () => console.log('Completes with Success!'),\r\n    });\n\n\n\/\/ Output\r\n\/\/ {vechicles: Array&#91;25], users: null, hackers: Array&#91;30], articles: null}\r\n\r\n\/\/ After 500 milliseconds\r\n\/\/ {vechicles: Array&#91;25], users: null, hackers: Array&#91;30], articles: Array&#91;26]\u2026}\r\n\r\n\/\/ After 2000 milliseconds\r\n\/\/ {vechicles: Array&#91;25], users: Array&#91;10], hackers: Array&#91;30], articles: Array&#91;26]}\r\n<\/code><\/pre>\n\n\n\n<p>For the sake of network delay, we introduced\u00a0<strong>delay<\/strong>\u00a0and\u00a0<strong>startsWith<\/strong>. So initially the users and articles property starts with\u00a0<strong>null<\/strong>\u00a0and as soon as the data is retrieved. Both the properties are populated with latest responses.<\/p>\n\n\n\n<p>And all responses are combined.<\/p>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<p>In conclusion, both <strong>forkJoin<\/strong> and <strong>combineLatest<\/strong> produce similar results but forkJoin emits the response only after all the Observables completes. Whereas with combineLatest, we can trigger  some Observable with &#8220;startWith&#8221; value, and let the operator emitting responses as soon as other Observable starts completing.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>RxJS (Reactive Extensions for JavaScript) is\u00a0a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code. This library offers us a lot of operators.One such operators are\u00a0forkJoin\u00a0and\u00a0combineLatest. forkJoin forkJoin\u00a0is a special operator from RxJx that let\u2019s you combine \/ accept multiple ObservableInputs and returns the objects of values with [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1963,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[37,5,83],"tags":[401,382],"_links":{"self":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/2358"}],"collection":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=2358"}],"version-history":[{"count":1,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/2358\/revisions"}],"predecessor-version":[{"id":2359,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/2358\/revisions\/2359"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media\/1963"}],"wp:attachment":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=2358"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=2358"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=2358"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}