Initiate a series of tasks and await their completion using RxJS / Redux Observables

My app requires an initialisation action to be fired, followed by a series of other actions before triggering another action. I found a similar question on Stack Overflow

However, when attempting this approach, only the initial APP_INIT action is executed, and none of the subsequent actions in the sequence. Can anyone provide assistance?

import { of } from 'rxjs';
import { mergeMap, zip, concat, mapTo } from 'rxjs/operators';
import { ofType } from 'redux-observable';
import { firstAction, secondAction } from 'actions';

export default function appInit (action$) {
  return (
    action$.pipe(
      ofType('APP_INIT'),
      mergeMap(() =>
        concat(
          of(firstAction()),
          of(secondAction()),
          zip(
            action$.ofType('ACTION_ONE_COMPLETE'),
            action$.ofType('ACTION_TWO_COMPLETE')
          ).mapTo(() => console.log('complete'))
        )
      )
    )
  );
}

Answer №1

It turns out that my code was almost perfect initially. The major issue was that I mistakenly imported concat from rxjs/operators instead of directly importing it from rxjs. It took me a considerable amount of time to identify this mistake, but now everything is functioning as intended.

For those who may benefit from it, I have included the complete code below.

import { of, concat, zip } from 'rxjs';
import { mergeMap, map, take } from 'rxjs/operators';
import { ofType } from 'redux-observable';

import { appInitialisationComplete, APP_INITIALISATION } from 'client/actions/app/app';
import { actionOne, ACTION_ONE_COMPLETE } from 'client/actions/action-one/action-one';
import { actioTwo, ACTION_TWO_COMPLETE } from 'client/actions/action-two/action-two';

/**
 * appInitialisationEpic
 * @param  {Object} action$
 * @return {Object}
 */
export default function appInitialisationEpic (action$) {
  return (
    action$.pipe(
      ofType(APP_INITIALISATION),
      mergeMap(() =>
        concat(
          of(actionOne()),
          of(actioTwo()),
          zip(
            action$.ofType(ACTION_ONE_COMPLETE).pipe(take(1)),
            action$.ofType(ACTION_TWO_COMPLETE).pipe(take(1))
          )
            .pipe(map(() => appInitialisationComplete()))
        )
      )
    )
  );
}

Answer №2

CombineLatest is the perfect solution, as it will only trigger when all observables have emitted.

const { combineLatest, of } = rxjs;
const { delay } = rxjs.operators;

combineLatest(
  of(1),
  of(2).pipe(delay(2000)),
  of(3).pipe(delay(1000))
).subscribe(([a,b,c]) => {
  console.log(`${a} ${b} ${c}`); // It will take 2 seconds as that is when all observables have emitted
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with AddToAny plugin not functioning properly on FireFox

I’m having issues with AddToAny for social media sharing on my website. It seems like FireFox is blocking it because of tracking prevention measures. Error Message in Console: The resource at “https://static.addtoany.com/menu/page.js” was blocked d ...

Problem with transitioning to a different page on Next.js

I am having trouble navigating to a different page in Next.js using the router.push function. The goal is to route to "example.js" by utilizing a variable called ChangePage, which leads to a single div element on that page. However, despite following the ...

Implement the AngularJS orderby filter based on a checkbox selection

Is it possible to use the angularJS orderby filter with a checkbox for ordering columns? I currently have this working as expected: <tr ng-repeat="player in players | orderBy:'id':true | rangeFilter:min:max"> <td>{{player.id}}</ ...

Having issues with clicking on a row in the table while using AJAX functionality

Experiencing a puzzling issue while attempting to add click functionality to table rows with AJAX, here is the JavaScript code used: //for tabs $(document).ready(function () { $("#tabs").tabs(); }); $(window).load(function() { jsf.ajax.addOnEven ...

Enhancing visual appearance with customized look control through the use of setAttribute

I have developed a unique custom look-controls feature and I am trying to integrate it into the scene using 'setAttribute(componentName, data)', but I'm unsure about what parameters to include. Any suggestions? Here is my approach: const s ...

JavaScript multiplying an array in HTML

Snippet of HTML code <input name="productCode[]" value="" class="tInput" id="productCode" tabindex="1"/> </td> <input name="productDesc[]" value="" class="tInput" id="productDesc" readonly="readonly" /></td> <input name="pr ...

Javascript - Relocating a file to a different folder in a node.js environment

I am looking to duplicate a file and relocate it within the directory structure. Current file location: Test.zip -> Account/Images/ -account.png -icon.png -flag.png . ...

What is the best way to include default text in my HTML input text field?

Is it possible to include uneditable default text within an HTML input field? https://i.stack.imgur.com/eklro.png Below is the current snippet of my HTML code: <input type="text" class="form-control input-sm" name="guardian_officeno" placeholder="Off ...

Customize the date format of the Datepicker in Angular by implementing a personalized pipe

I am dealing with a datepicker that defaults to the MM/dd/yyyy format, and I need it to adjust based on the user's browser language. For example, if the browser language is English India, then the format should be set to dd/MM/yyyy as shown below. Be ...

Displaying Stats.js inside a different canvas using ThreeJS

Just starting out with Three.js and wanted to test displaying the Stats.js in a small scenario. Check it out here Decided not to use modules for now, but followed similar code structure as in the examples: var stats = new Stats(); var renderer = ...

Input information into a JSON container

I've been struggling to find a solution for this issue. Here's the JSON variable I'm working with, which includes the names "rocky" and "jhon": var names = [ "rocky", "jhon" ]; Now, I need to add a new val ...

Using the `ng-if` directive in Angular to check for the

I need to output data in JSON format using items. To display a single item, I utilize ng-repeat="item in items". Additionally, I can access the user object of the currently logged-in user with user. Every item has the ability to belong to multiple wishlis ...

Streamline email error management within nested middleware functions

I have implemented an express route to handle password resets, which includes finding the user and performing some error handling. However, I am now faced with the challenge of adding additional error handling within a nested function, and I am uncertain a ...

How can I convert a Java array of arrays into JavaScript?

When working with Java, I need to create a JSON structure similar to this: [ [ timestamp , number ],[ timestamp , number ] ] This structure is necessary for displaying data on Highcharts graphs. I initially used a "LinkedList of LinkedList" format to ...

Python.Selenium. Unable to locate current element. Techniques for switching frames

I am trying to collect feedback from a specific page at this URL. After waiting for the page to load, I attempted to locate elements using Google Chrome inspector. However, Selenium is unable to find these elements, and I also could not find them in the p ...

What is the best way to adjust the screen to display the toggle element when it is opened?

Here is the code I'm currently using to create a toggle button that shows or hides extra content when clicked: $(".toggle .button").click(function() { $(this).next().slideToggle('fast'); }); The issue I am encountering is that if t ...

Cease the use of jQuery animations

My JavaScript code snippet looks like this: $.get("/<page>.php", "userid='.$userid.'&"+status, function(data){ $("#status").show("fast").html(data).delay(4000).hide("fast"); }); On a page with multiple links triggering thi ...

Javascript increasing the variable

Whenever I interact with the code below, it initially displays locationsgohere as empty. However, upon a second click, the data appears as expected. For example, if I input London, UK in the textarea with the ID #id, the corresponding output should be var ...

Building a dynamic tab menu using JavaScript: A step-by-step guide

In order to generate dynamic tab menus with JavaScript, I am seeking a solution that does not rely on jQuery as it may not be supported by all mobile devices. Any advice for replicating the same functionality using pure JavaScript would be greatly apprec ...

Guide to storing a collection in an object with Java

Before the changes were saved https://i.stack.imgur.com/hjpXa.jpg After the changes were saved https://i.stack.imgur.com/xABzN.jpg @Entity @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class Notification { @Id @GeneratedVa ...