what is the best way to pause for an observable and then provide the previous observable outcome in rxjs?

A specific sequence needs to be executed in the following steps:

  1. read a small piece of data
  2. clear the data storage
  3. re-save the small piece of data from step 1

Each operation has its own method that returns an Observable. The sequence suggested is as follows:

this.storage.get('key').pipe(
  switchMap((x) => this.storage.clear().pipe(map(()=>x))),
  switchMap((x) => this.set('key', x)
);

The repetitive use of switchMap() seems cumbersome. Although the sequence works, it might benefit from simplification.

An attempt was made using concat() at first, but it emitted values individually. Additionally, merge could not be utilized as it would run the observables simultaneously and we need to ensure that the .clear() function does not execute concurrently with either .get() or .set().

Is there an appropriate operator or creation function that can achieve the following:

  • initiate the first Observable
  • wait until the first Observable starts before triggering the second one
  • then return an array or map containing both results

Alternatively, is there a simpler way to handle the double call to switchMap()?

Answer №1

Consider implementing delayWhen operator

this.dataStore.retrieve('key').pipe(
  delayWhen(() => this.dataStore.reset()),
  switchMap((result) => this.saveData('key', result))
);

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

Clerk Middleware experiencing unexpected malfunctions

After installing Next.js 14 for my project, I decided to set up authentication with Clerk before getting started. Despite configuring the middleware.ts and layout.tsx files and running npm run dev, the terminal showed that the /middleware was compiled. How ...

What is the best method for validating variadic mapped tuple arguments while maintaining the inferred generic types?

My situation involves a higher order function called `createHandler`, which takes rest arguments in a variadic mapped tuple format and maps them to a generic object type (let's call it `ObjA<>`). The function returned can then be passed to anoth ...

creating a map of a collection of elements

I'm seeking suggestions on how to achieve this task. The getAllData function returns an array of objects, and I need to iterate through each object resulting from getAllData and extract the id of objects with Type-A. Subsequently, I aim to use each id ...

Issue encountered while executing the Docker run command: EEXIST - The file already exists as a symbolic link from '/app/node_modules' to '/app/.build/node_modules'

I've encountered an issue while trying to run a Node.js TypeScript app with Docker. The Dockerfile I'm using builds the image successfully: FROM lambci/lambda:build-nodejs6.10 # Set up the app directory WORKDIR /app # Install app dependencies ...

The Angular Material table is not populating with the data from the data source

I'm currently working on a project to create a table of stock quotes using the IEX trading API. However, I've encountered some issues while trying to connect it to the data source. Although I can use ngFor to display the data, I'm facing dif ...

Using TypeScript with React and Material-UI: Issue with undefined theme in createStyles()

Currently, I am delving into React with TypeScript and utilizing the Material UI framework for the frontend. In my quest to activate media queries, an error has crossed my path: Uncaught TypeError: Cannot read property 'up' of undefined ...

What causes an error during the compilation of an Angular package containing a singleton class?

I am currently in the process of creating an Angular library. Within this library, I have developed a singleton class to manage the same SignalR connection. Here is the code implementation: import * as signalR from '@microsoft/signalr'; export c ...

What is the best way to combine a Signal containing an array of Signals in Angular using the merge(/mergeAll) operator?

When working in the world of rxjs, you have the ability to combine multiple Observables using the merge operator. If you have an array of Observables, all you need to do is spread that array into the merge operator like this: merge(...arrayOfObservables). ...

Best Practices for Enhancing Testability of Wrapper Methods

Recently, I have implemented a practice in my tests where I encapsulate error messages and string manipulations into methods or variables to enhance the resilience of my tests in case the content of error messages changes in the future. For instance, I wo ...

Snapshots testing app Expo TypeScript Tabs App.tsx

After setting up an Expo project with Typescript and Tabs, I decided to add unit testing using Jest but ran into some issues. If you want to create a similar setup, check out the instructions here: . Make sure to choose the Typescript with Tabs option whe ...

Tips for saving images to a local directory with Angular2

I am a beginner on Stack Overflow and new to Angular 2. I am currently learning how to upload images to a local folder within my Angular 2 application. I have been struggling to understand how to save images in a local folder. Many of the answers I found o ...

What is the best way to retrieve input value across various components?

I am working with two components: headerComponent and searchPageComponent. I need to ensure that whatever value is entered in the header component's search bar, it should be accessible in the search page component. header.component.html <fo ...

Setting up event listeners from a string array (using PIXI.js)

Hey there! I've encountered a bit of an interesting challenge that could easily be resolved by duplicating the code, but where's the fun in that? This project is more of an experiment for me, just to prove that I can do it. However, the idea has ...

Is your Angular 2 Observable malfunctioning?

sendMessage(message: string, recipient: string){ console.log(message, recipient, this.user); let newMessage = {from: this.user['name'], msg: message}; this.sub = this.route.params.subscribe( params => { let name = recipient ...

New from Firefox 89: The afterprint event!

Having an issue with this fragment of code: const afterPrint = () => { this.location.back(); window.removeEventListener('afterprint', afterPrint); }; window.addEventListener('afterprint', afterPrint); window.print(); I&apos ...

Header sticks motionlessly when appearing, no animation when vanishing

edit: check out my sandbox https://codesandbox.io/s/nostalgic-morning-3f09m?file=/src/App.tsx I have a sticky header implemented in React/Gatsby that should become visible when the screen is scrolled to Y >= 420. Once it reaches this point, an animatio ...

Display a React component according to the user's input

Within the first (parent) div, there is an underlined message stating: "This JSX tag's 'children' prop expects a single child of type 'ReactNode', but multiple children were provided.ts(2746)". import A from './components/A&ap ...

Leveraging ng-repeat following an asynchronous $http request

I am currently diving into Angular (1.6.6), and I have a feeling that I might be overlooking something fundamental. By fetching JSON data from the database, I am able to populate a dropdown menu on ng-init successfully. Upon inspection using console.log() ...

Importing from source code instead of a file in TypeScript: How to do it

I found this code snippet to help with dynamic component loading: loadComponent(name) { var url = this.configurationService.configuration.api_url+"/generator/dynamic-loading/component/"+name; this.http.get(url, {responseType: 'text'}). ...

What is the best way to set a variable as true within a pipeline?

Could someone assist me with a coding issue I'm facing? If the id is null, I need variable x to be true. I am unable to use if and else statements within the pipe. Any guidance would be greatly appreciated. private x = false; private y = false; n ...