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

Assigning a specific data type value to an element as it enters the top of the viewport

I have a unique color code stored for each section, and when a section reaches the top of the screen (specifically -180px for the header), I want to dynamically change the text color of the header element as you scroll through the sections. Despite no erro ...

If there are multiple instances of the component, it may not function properly

I have implemented a Vue component as shown below: <script setup lang="ts"> import { PropType } from "nuxt/dist/app/compat/capi"; interface Star { id: string; value: number; } const stars: Star[] = [ { id: &qu ...

Can test files be placed under the pages directory in a Next.js project?

Currently, I am in the process of writing integration tests for the API routes within a Next.js application. One question that has arisen is whether it would be problematic to place the index.test.ts file under the /pages directory. My preference leans tow ...

ES6 scoping confusion: unraveling the mystery

I stumbled upon these two syntax methods for exporting functions. Let's say we have files named actions.js and app.js. The first method looks like this: in actions.js export function addTodo() {} export function deleteTodo() {} and in app.js I have ...

Looking for a method to substitute "test" with a different value

Showing a section of the menu using <li id="userInfo" role="presentation" data-toggle="tab" class="dropdown"> <a href="#" name="usernameMenu" class="dropdown-toggle" data-toggle="dropdown" role="button"> <span class="glyphicon glyph ...

Ensure the browser back button navigates to the login page seamlessly, without displaying any error

A scenario I am working on involves a Login jsp that accepts a user email and sends it to a servlet. If the provided email is not found in the database, the servlet redirects back to Login.jsp with an attribute "error". Within the header of Login.jsp, ther ...

Include images in the form of .png files within the td elements of a table that is dynamically generated in the index

I have successfully created a table using embedded JavaScript with the help of messerbill. Here is the code: <table id="Table1"> <tr> <th>Kickoff</th> <th>Status</th> <th>Country</th> < ...

Using both Typescript and Javascript, half of the Angular2 application is built

My current project is a large JavaScript application with the majority of code written in vanilla JavaScript for a specific platform at my workplace. I am looking to convert this into a web application that can be accessed through a browser. I believe thi ...

When aggregating data using Mongoose expressions, Number, Boolean, and ObjectId types are not compatible

I am facing an issue with my query: const match: PipelineStage.Match = { $match: { deleted: false, provinceId: new mongoose.Types.ObjectId(req.params.provinceId), }, }; const query: PipelineStage[] = [match]; const c ...

Sending information into MySQL using NodeJS with the help of Postman

As a newcomer in the field, I am exploring how to combine MySQL with nodeJS for integrating projects into WordPress. app.post('/users/add', (req, res) => { id = req.body.id, firstname = req.body.firstname, surname = req.body.surname ...

Automatic Formatting of Typescript in SublimeText

Utilizing Microsoft's Typescript Sublime Plugin, I am able to format a file using the shortcut ^T ^F as outlined in the plugin's feature list. Is there a method to automatically execute this command when saving a file? Similar to the functionali ...

Is it possible to enable password authentication on Firebase even if the user is currently using passwordless sign-on?

In my frontend JS project, I have integrated Firebase for web and am utilizing the passwordless (email link) authentication method for users. I am now interested in implementing password sign-on for an existing user who is currently using passwordless si ...

Avoiding Bootstrap loading in a Hyperledger Composer application

I am looking to eliminate the Bootstrap stylesheet from my Hyperledger Composer-compiled project. After compiling using yo hyperledger-composer and then running npm start, I noticed that when src/index.html is served at http://localhost:4200/, a Twitter B ...

Tips for preserving updates following modifications in Angular 5/6?

I'm currently working on enhancing the account information page by implementing a feature that allows users to edit and save their details, such as their name. However, I am encountering an issue where the old name persists after making changes. Below ...

Implementing TypeScript type definitions for decorator middleware strategies

Node middlewares across various frameworks are something I am currently pondering. These middlewares typically enhance a request or response object by adding properties that can be utilized by subsequent registered middlewares. However, a disadvantage of ...

Navigation arrows for sliding`

Is there a way to add custom right/left arrows to the Ionic slider component? Demo: Check it out on Stackblitz Note: Make sure to refer to the home.html page for more details. https://i.sstatic.net/jQ62l.png .html <ion-slides [pager]="true" [slide ...

Material-UI chart displays only loading lines upon hovering

Currently, I am utilizing a Material UI Line chart in my NextJS 14 application to showcase some data. Although the data is being displayed properly, I have encountered an issue where the lines on the chart only render when hovered over, rather than appeari ...

establish the data type for the key values when using Object.entries in TypeScript

Task Description: I have a set of different areas that need to undergo processing based on their type using the function areaProcessor. Specifically, only areas classified as 'toCreate' or 'toRemove' should be processed. type AreaType ...

What is the best way to attach a Label to a THREE.Mesh object?

I'm looking to show the name of a Three.js Three.Mesh as a label when hovering over the mesh. Does anyone know how to achieve this in Three.js? Could someone provide an example code snippet for this? ...

Unable to access the response body of a POST request from an external API within Firebase Cloud Functions

I am encountering an issue with my cloud function in which it makes an http POST request to the LinkedIn API for retrieving an access token. The main problem is that I am unable to retrieve the `body` of the response as it always turns out to be `undefined ...