Tips on ending an interval in rxjs once it has started

Implemented a code in an Angular component to retrieve data from a service every 10 seconds on initialization. Now, I need to find a way to stop the interval after a certain period of time such as 5 minutes or when all the necessary data has been collected.

Below is the code snippet for the component:

GetRecords() {
  Interval(10000).pipe(
    startWith(0),
    switchMap(() => this.getService.getData())
  ).subscribe(data => {
    this.code = data;
  });
} 

Answer №1

If you ask me, I believe using rxjs timer would be more suitable for this situation. Here's how:

const source = timer(0,10000);
source
.pipe(take(6*5),//taking until 5 minutes i.e. 30 times
takeWhile(()=>a==b))//your specified condition
.subscribe()

Answer №2

To stop receiving updates, you must unsubscribe from the observable.

private intervalSub: Subscription;

Getrecords() {
  this.intervalSub = Interval(10000).pipe(
    startWith(0),
    switchMap(() => this.getservice.getdata())
  ).subscribe(data => { this.code = data });
}

cancelInterval() {
  if (this.intervalSub)
    this.intervalSub.unsubscribe();
}

You can manually invoke the cancel function after a specific point or in the OnDestroy lifecycle hook (ensure component implements OnDestroy):

ngOnDestroy() {
  this.cancelInterval();
}

There are alternative methods to canceling an observable, like using operators to complete it, for example, take(20) limits observations to 20. Another option is utilizing the async pipe for Angular's automatic handling, but the provided method is reliable.

Answer №3

Enhancing the previous User3250's response by utilizing switchMap

const timerSource = timer(0, 10000);
    timerSource
    .pipe(take(6*5), // take up to 5 minutes, which is 30 times
    switchMap(() => this.service))
    .subscribe()

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

Exploring the magic of Angular 4's FormBuilder: creating dynamic FormControls within a

My application enables users to choose from a dropdown menu of events, each with its own unique properties and selectable property values. This is achieved by creating a FormGroup for each event, with a FormControl for each property. Upon initialization, ...

Angular 2: Utilizing Http Subscribe Method with "this" Context Pointer

Question: http.request('js/app/config/config.json').subscribe(data => { this.url = data.json().url; }); It seems that "this" is pointing to Subscriber instead of the parent class. I was under the impression that the fat- ...

Navigating conflicts between packages that utilize TypeScript can be tricky. Here are some strategies for handling these situations

I recently encountered an issue while following a tutorial to create a WhatsApp clone using Meteor. The tutorial link is here The problem arose at the end of section 8 when I executed the $meteor reset command as directed. However, upon running the $ n ...

How can we eliminate the need for specifying the order of generic arguments in TypeScript?

In the development of my middleware engine, I have incorporated various generic arguments that are specific to the particular implementation in use. export type Middleware< Store = never, Args = unknown, Response = unknown > = ( context: { ...

Dealing with race conditions in Angular 2 nested resolvers and managing them effectively using RX

Back with an intriguing predicament! Currently, I am in the process of developing an angular2 application using RXjs observable data stores to supply data to my app. Upon launch, if a user is logged in, the app resolvers fetch the relevant user data and po ...

Effortlessly passing props between components using React TypeScript 16.8 with the help

In this scenario, the component is loaded as one of the routes. I have defined the type of companyName as a string within the AppProps type and then specified the type to the component using <AppProps>. Later on, I used {companyName} in the HTML rend ...

Leveraging Component without the need for Import

Is it possible to use a component without re-importing it if it's already declared in AppModule? With 10 or more pages/components to manage, importing each one can be challenging. Here is my app.module.ts import { NgModule, ErrorHandler } from &apos ...

Navigating a SwipeableDrawer in React with scrolling functionality

I'm currently using a swipeable drawer in React from MUI to display lengthy content. My goal is to keep the title visible even when the drawer is closed, and I was able to achieve this through the following method: MUI SwipeableDrawer I've provi ...

Required attributes not found for data type in TypeScript

When the following code snippet is executed: @Mutation remove_bought_products(productsToBeRemoved: Array<I.Product>) { const tmpProductsInVendingMachine: Array<I.Product> = Object.values(this.productsInVendingMachine); const reducedPro ...

Nested component in reactive forms not functioning as expected

I've been experimenting with creating nested reactive form components. Specifically, I'm working on a reusable input component for my app within a reactive form. How can I dynamically communicate with nested components in Reactive forms? Despite ...

Angular: NaNa: Attempting to access a property of an undefined variable

I've encountered these errors although the values are displayed correctly in the browser. I'm unsure about how to resolve this issue. ERROR TypeError: Cannot read property 'length' of undefined ERROR TypeError: Cannot read property &ap ...

The element's 'nativeElement' property cannot be accessed because it is undefined

I have a scenario where I have a parent component and a child component. I am trying to access the DOM element of the Child component from the Parent component, but I keep encountering an issue with the native element being undefined. export class ChildCom ...

Error encountered when trying to create a Google Calendar event using the Google Calendar API on a Google business account with writer access

Utilizing the Google Calendar API within my Angular 9 Web Application, I am attempting to create events on a Google Calendar in my G Suite domain. Within the G Suite Admin Console, I have granted the service account permissions for the scopes and I have ...

Tips for presenting random images from an assortment of pictures on a webpage

I'm looking to enhance my website by adding a unique feature - a dynamic banner that showcases various images from a specific picture pool. However, I'm unsure of how to find the right resources or documentation for this. Can you provide any guid ...

Having difficulty resolving sub-modules using webpack

Currently, I am trying to set up the @microsoft/signalr npm package with webpack by importing the module using import * as signalR from '@microsoft/signalr'. However, I encountered an error message indicating that webpack is unable to resolve the ...

The alterations made to a single dropdown option are causing ripple effects across all other dropdowns

There is an add button that continuously adds a div container containing two dropdowns. The selection in one dropdown affects the data in the other dropdown. When the add button is clicked, a second div with both dropdowns is added. However, changing the ...

A TypeScript default function that is nested within an interface

This is functioning correctly interface test{ imp():number; } However, attempting to implement a function within the interface may pose some challenges. interface test{ imp():number{ // do something if it is not overwritten } } I am ...

Unexpected token in catch clause in React Native TypeScript

Despite having a fully configured React Native Typescript project that is functioning as expected, I have encountered a peculiar issue: Within all of my catch blocks, due to the strict mode being enabled, typescript errors are appearing like this one: htt ...

Struggling to retrieve service information for implementation in the component

I am currently working on a project where: 1. I have created a news.service.ts service file with the following code: 2. Within the service, I have implemented a function named throwData() that returns the service data. Here is the code snippet: im ...

"Mastering ngb-pagination in Angular 4: A Step-by-Step

I need help with implementing ngb-pagination. I've tried following solutions from similar questions but they didn't work for me, so I am posting my question again. I am lost on how to successfully integrate ngb-pagination into my project. < ...