``Infinite loops in rxjs: how to create a never-ending task

I'm working on a never-ending task that needs to loop continuously in TypeScript.

The next task should only start when the previous one has finished.

I've decided to utilize rxjs for this because it appears to be the most concise approach.

My attempts with interval, queue scheduler, defer, exhaust, and exhaust map haven't been very successful so far.

This is my current code snippet:

function longTask(): void {
    // some lengthy process
}

interval(1000)
.pipe(
     exhaustMap((x) => 
         defer(()=> longTask())
     )
.subscribe();

Any assistance would be greatly appreciated.

Answer №1

Utilize the zip function, which will trigger the interval and then pause for your observable to be triggered.

zip(interval(1000), longTask()).subscribe(([_, longTaskResult]) => {
});

Alternatively, if your longTask only emits once and completes, you could implement a recursive call

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

const longTask = () => of(Math.random() * 10).pipe(delay(Math.floor(Math.random() * 5000)));

const runLongTask = () => {
  longTask().subscribe(result => {
    console.log(result);
    runLongTask();
  });
}

runLongTask();
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/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

Utilizing WebPack 5 in conjunction with Web workers in a React/Typescript environment

Can someone help me figure out how to make a web worker function properly with create-react-app, Typescript, and Webpack 5? I've been struggling with limited documentation and can't seem to find a clear explanation. I'm trying to avoid using ...

Tips on maintaining the chosen product while navigating to a different component

I have a dilemma with 2 different components that are responsible for creating an invoice. The first component adds more products The second component adds invoice details Initially, I enter the invoice details and select the client's name. The sel ...

The generation of the .prisma folder in the Node process is causing a file lock, which is hindering the progress of future

Node: 20.11.1 Azure Pipeline: Ubuntu 22.04.4 LTS Prisma: 5.10.2 I am currently utilizing an Azure pipeline to run a typescript-based ExpressJS application. Displayed below is the contents of my package.json: { "name": "...", & ...

typescript React-Redux challenge: Boosting Your mapDispatchToProps Skills

I'm having trouble determining the type of my mapDispatchToProps function in the SignInComponent. See the code snippet below: Here is my authAction.ts file: import firebase from 'firebase/app' import { Dispatch } from 'react'; ty ...

Is there a way to retrieve all elements from the array with the specified type definition of item(index: number): any?

I am currently working on a React Native project, but I have a TypeScript query. The SQLite embedded database is set up and I am trying to retrieve the entire array of rows. However, I am facing an issue with the object structure. https://i.sstatic.net/74 ...

What is the process of branching a stream with highland.js?

I have a stream called sourceStream that contains objects of type BaseData. My goal is to split this stream into n different streams, each filtering and transforming the BaseData objects according to their specific criteria. Ultimately, I want to end up ...

Obtain characteristics of the primary element in Ionic version 2 or 3

After creating and opening my Sqlite database and saving the SQLiteObject in a variable within my app.component.ts, I now need to retrieve these attributes in my custom ORM. The ORM extends to other providers to describe the title and field of my tables. ...

Should private members be kept confidential during program execution?

While Typescript's "private" members may not be truly private at runtime, traditional closures maintain the privacy of their members. Is there value in ensuring that private members remain private during runtime? ...

obtaining data from an HTML input field

I'm struggling to retrieve the value from an HTML input element, and despite my own research, it seems like I have the correct syntax. However, I'm still unable to get it to work, leaving me confused. When I log the value to the console, it appe ...

The process of linking a specific type to a generic function behind the scenes

In my particular situation, I have a class (for example "Collection") that is aware of the type it is dealing with (such as "DBType"). The constructor of this class receives a generic function (like "Transform") which takes the subtype of DBType and return ...

Generating Enums from JSON REST API in Angular 8

Is there a way to create an enum from a JSON REST API? Here is the code I currently have in my service.ts file: getDataFromJson(): Observable<any> { return this.httpClient.get<any>(`../../../assets/gender.json`) .pipe(map(data => ...

Exploring the benefits of using TypeScript with Angular2 for HTTP

I have a locally stored "region.json" file containing the following data: { "regionId":1, "region":"CAN" }, { "regionId":2, "region":"CEN" } Additionally, I have an "enviroment-app.component.ts" file structured as follows : import {Component, ...

Best practices for updating the value of a specific key within an object that contains recursion in JavaScript/TypeScript

I have a tree component that uses the following data structure type TreeNode = { id: string, parentId: string, renderer: () => React.ReactNode, expanded: boolean, children?: Array<TreeNode>, } Now, I am looking to add functionality for ...

What is the best way to pass an array through router navigate function?

I've searched for a solution in other questions, but nothing has helped me... My goal is to redirect to a URL like this: this.router.navigateByUrl('/products'); I want to pass an array and retrieve it in the component with the active link ...

The process of automatically formatting Typescript has transformed into an unfortunate auto-discarding action

Typescript autoformatting has become a concerning issue. Whenever I input quoted strings (" or `), the code surrounding it seems to temporarily glitch, with other strings appearing as code. This problem has recently escalated, particularly with strings li ...

The element is inherently an 'any' type as the expression of type 'number' does not have the capability to index type 'Object'

Hey there, I'm currently in the process of learning Angular and following along with the Note Mates tutorial on YouTube. However, I've hit a stumbling block as I attempt to implement sorting by relevancy. The issue lies with the code snippet belo ...

Issue: The CSS loader did not provide a valid string output in Angular version 12.1.1

I am encountering 2 error messages when trying to compile my new project: Error: Module not found: Error: Can't resolve 'C:/Users/Avishek/Documents/practice/frontend/src/app/pages/admin/authentication/authentication.component.css' in &apos ...

Stop WebStorm from automatically importing code from a different Angular project within the same workspace

I currently have an angular repository that consists of two projects: a library and an Angular application. To link the library to my project, I utilized the npm link command. Within the package.json file, I specified the entry as follows: ... "my-lib ...

I possess an item that I must display its title as a <choice> in a <menu> while returning a different variable

I am working with an object: company: { name: 'Google', id: '123asd890jio345mcn', } My goal is to display the company name as an option in a material-ui selector (Autocomplete with TextField rendering). However, when a user selects ...

Encountered an issue in React and Typescript where the argument type is not compatible with the parameter type 'EventListenerOrEventListenerObject'

One challenge I am facing is integrating Typescript into my React project: componentDidMount() { document.addEventListener('mousemove', this.handleMouseMove); } private handleMouseMove = (e: React.MouseEvent<HTMLElement>) => { appS ...