Ways to Halt observable.timer in Angular 2

As I work on Angular2's Component, I am currently implementing the following functions:

export class MypageEditComponent {

  ngOnInit() {
    this.timer = Observable.timer(100, 100);
    this.timer.subscribe(t => {
      this.setFormData();
  }


  private setFormData() {
    this.editUserAcountType = this.authStore.registerInfo.account_type;
    this.editAddress = this.authStore.registerInfo.email;
    this.editUserName = this.authStore.registerInfo.username;
  }
}

I am trying to figure out how to stop the repetition of Observable.timer once the data is correctly stored using setFormData().

If you have any ideas on how to achieve this, please let me know.

Answer №1

There are essentially two methods:

  • invoke unsubscribe() on the Subscription object received from the subscribe() method .
  • utilize an operator

To solely unsubscribe, you can accomplish it like so.

ngOnInit() {
  this.subscription = timer(100, 100).subscribe(t => {
    this.setFormData();
  });
}

private setFormData() {
  ...
  this.subscription.unsubscribe();
}

Alternatively, you can utilize Subject to finalize the Observable using the takeUntil() operator:

this.subject = new Subject();

ngOnInit() {
  timer(100, 100).pipe(
    takeUntil(this.subject),
  ).subscribe(t => this.setFormData());
}

private setFormData() {
  ...
  this.subject.next();
}

Also check out these resources:

  • Difference between .unsubscribe to .take(1)
  • RxJS: takeUntil() Angular component's ngOnDestroy()

January 2019: Updated for RxJS 6

Answer №2

When you need to stop a timer observable, simply use the unsubscribe method as shown below:

this.timer = Observable.timer(100, 100);
this.subscription = this.timer.subscribe(t => {
    this.setFormData();
});

.............
this.subscription.unsubscribe();

Answer №3

An aspect not yet addressed by previous responses is that there's no necessity to actively halt an observable timer/interval - especially not through direct interaction with the observable or the timer itself.

I came across this realization while setting up an observable using a timer in the start method of a HostedService. When it was time to stop, I thought I should be stopping or disposing of something, right? Well... not exactly. The observable timer doesn't require being stopped or disposed of in that manner; only the subscriptions need to be cleared, and here's why...

Observable timers and intervals are classified as cold streams (even though they may give the impression of being hot). They remain passive until subscribed to, do not generate data until then, and cease producing data when there are no subscribers. As such, removing all subscriptions should suffice in halting the timer from generating data.

For more information, visit: [

Answer №4

Have you ever considered turning it into a promise instead?

import { timer } from 'rxjs';

timer(1000).toPromise().then(res => {
      //your code can go here
})

No more worrying about unsubscribing.

Answer №5

-- temporary fix

setInterval(() => observer.notify(), 2000);

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

Is there a mistake in the TypeScript guide for custom typography in MUI5?

Currently, I am in the process of setting up custom typography variants in MUI5 by referencing this helpful guide: https://mui.com/customization/typography/#adding-amp-disabling-variants. As I follow step 2 and input the type definitions: declare module &a ...

What causes delayed state updates in React/NextJS until another state is updated or a fast refresh occurs?

UPDATE: Version 13.3.0 is coming soon! In my code, I have a state variable named localArray that I need to update at a specific index. To achieve this, I decided to create a temporary array to make modifications and then set the state with the updated val ...

Efficient method for iterating through three arrays that have matching values and satisfy specified conditions in TypeScript

Struggling to speed up my Excel sheet creation time, currently taking over 20 seconds. I'm using the code below to compare three arrays and get the desired output: for (let i = 0; i < this.arrayNumberOne[0].length; i++) { let orangeOne = this.a ...

Tips for implementing personalized command buttons in Kendo Grid with AJAX request utilizing JavaScript

I am struggling with implementing custom command buttons in a Kendo grid that makes an AJAX call using JavaScript to call a web API post action with dynamic parameters (start, stop, restart) behind button clicks. datasource dataSource = new ken ...

Develop a plugin architecture using JavaScript and Node.js

Here is a basic implementation using node.js with express: var express = require('express'); var app = express(); app.get('/', function(req, res){ res.send('Hello World'); }); app.listen(3000); I am interested in creatin ...

The issue with executing event.keyCode == 13 in Firefox remains unresolved

I've implemented a function that sends comments only when the "enter" key is pressed, but not when it's combined with the "shift" key: $(msg).keypress(function (e) { if (event.keyCode == 13 && event.shiftKey) { event.stopProp ...

Trouble with document updates in MongoDB/Mongoose causing a delay?

I am currently working on updating an object nested in an array in my application. When I test this functionality using Postman, I am experiencing a delay that requires me to make two requests in order to see the updated value. if (taskStatus) { cons ...

An issue with JSPDF arises when used on mobile devices

Currently, I am working on a project to create a responsive web application, which involves utilizing JSPDF for generating PDF reports directly from HTML. For a demonstration of the functionality, you can check out this Demo. Unfortunately, when trying t ...

REACT performance impacted by slow array filtering

I have a custom listbox feature, where a div holds a vertical list of other div elements. There is also an input field for searching within the list. While it works fine with small data sets, it becomes extremely slow with large amounts of data. In additi ...

Navigating the Angular2 @angular/router 3.0.0-alpha.3 - Ways to access the route name or path upon route transitions

In my app.component, I am currently looking for a way to access the current route name or path when the route changes. My goal is to use the route name as a page class for a wrapper div. I had previously been subscribing to the router changes property as ...

AngularJS tips for resolving an issue when trying to add duplicates of a string to an array

Currently dealing with a bug that occurs when attempting to push the same string into an array that has already been added. The app becomes stuck and prevents the addition of another string. How can I prevent the repeat from causing the app to get stuck w ...

Issue with swal() not triggering in Internet Explorer 11

Looking for some assistance here, I believe I might be missing a small detail. The _layout.cshtml file includes all the necessary scripts to ensure that sweetheart works on IE: (this used to work in previous versions, but we haven't had to support I ...

Creating a sliding menu using React and Headless UI (with Tailwind CSS)

Currently, I'm in the process of developing a slide-over navigation bar or slide menu that features panels opening on top of each other (I'm still searching for the most accurate way to describe it). The main concept revolves around having a sli ...

I'm having trouble persisting my mongoose model data in my MongoDB database

Hey there, I'm new to this and currently attempting to save the Amadeus object I've created into mongosh using the .save() method. However, after connecting to my file through node, editing the Amadeus object, and running amadeus.save(), I check ...

What is the best way to insert a chart into a div using *ngIf in Angular?

I just started using chart.js and successfully created the desired chart. However, when attempting to implement two tab buttons - one for displaying tables and the other for showing the chart - using *ngIf command, I encountered an error: Chart.js:9369 F ...

Obtaining JSON data in an Angular service: A beginner's guide

My JSON file has the following structure: { "user": [ { "id": 0, "data": [ { "userName": "iheb", "useremail": "", "userPassword": "kkk" } ], "questionnaireListe": [ { ...

Is it possible to refresh resources in Node.js without the need to restart the server?

Is there a middleware or library that allows access to files added after the server starts without requiring a restart? I currently use koa-static-folder, but it seems unable to handle this functionality. ...

How can I remove a row from a mat table using Angular?

Having trouble implementing *ngFor in my angular mat table, seeking guidance from someone with more expertise? I am trying to delete a row within an array using a button and display it on my table, but encountering issues. I intend to utilize *ngFor to sh ...

The AnimationRendererFactory ahead-of-time (AOT) compilation is encountering an issue where it is unable to access the property 'create

I am encountering an issue while trying to compile my Angular4 app AOT. The error message that I am stuck on is: TypeError: Cannot read property 'createRenderer' of undefined at AnimationRendererFactory.createRenderer (http://localhost:8080/cwp/ ...

Enhancing CKEditor: Inserting new elements upon each dialog opening

I am facing a challenge where I need to dynamically add varying numbers of elements to a dialog window each time it is opened. Below is the code I am working with: CKEDITOR.on( 'dialogDefinition', function(ev) { var dialogName = ev.data.name ...