What are the steps to resubscribe after opting out?

My Angular service has three attributes and two functions:

timerSubscription: Subscription;
pollingSubscription: Subscription;
incrementTimerSubscription: Subscription;

async startTimer(idTask: number) {
  this.timerSubscription = this.folderService
    .getTimerForTemplate(idTask)
    .pipe(
      tap(res => this.timer$.next(res.seconds)),
      switchMap(() => this.folderService.startTimerForTemplate(idTask))
    )
    .subscribe(() => {
      this.setMyState({ idTask: idTask, isTimerStarted: true });

      this.incrementTimerSubscription = interval(1000)
        .pipe(
          tap(() => {
            this.timer$.next(this.timer$.value + 1);
          })
        )
        .subscribe();

      this.pollingSubscription = interval(20000)
        .pipe(
          switchMap(() => {
            return this.folderService.incrementTimerForTemplate(idTask);
          })
        )
        .subscribe();
    });
}

incrementAndStartTimer(idTaskToIncrement: number, idTaskToStart: number, automaticSwitch?: boolean) {
  if (this.timerSubscription) {
      this.timerSubscription.unsubscribe();
    }
    if (this.pollingSubscription) {
      this.pollingSubscription.unsubscribe();
    }
    if (this.incrementTimerSubscription) {
      this.incrementTimerSubscription.unsubscribe();
    }

    if (automaticSwitch) {
      this.folderService
        .incrementTimerForTemplate(idTaskToIncrement, automaticSwitch)
        .pipe()
        .subscribe(() => {
          this.startTimer(idTaskToStart);
        });
    } else {
      this.folderService
        .incrementTimerForTemplate(idTaskToIncrement)
        .pipe()
        .subscribe(() => {
          this.startTimer(idTaskToStart);
        });
    }
}

After successfully calling the startTimer function, I face an issue when trying to call it again after using the incrementAndStart function to unsubscribe from existing subscriptions. This problem arises because the previous subscriptions have been unsubscribed. How can I resolve this issue?

Answer №1

Avoid nesting subscribe() inside another subscribe().

startTimer does not require async as there are no promises involved. Remove async.

Remove the unnecessary call to .pipe().

Here's a simplified version:

 if (this.timerSubscription) {
    this.timerSubscription.unsubscribe();
 }
// Simplified using ?. operator
this.timerSubscription?.unsubscribe();

If you're facing issues, have you debugged to see which code is being executed and where it stops? Are there any error logs?

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

When utilizing WPF WebBrowser with a local Angular 8 website, the window.external feature works flawlessly. However, complications arise when

Apologies for any formatting issues, this is my first post. I have been working on updating a legacy app with a new UI. This serves as a proof of concept to demonstrate our ability to create a thin client and host our project online. In my WPF window (.NE ...

ERROR : The value was modified after it had already been checked for changes

Encountering an issue with [height] on the main component and seeking a solution Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '753'. Current value: '731'. I have th ...

Looking to organize an array of objects containing two string elements (countries) based on the country name using TypeScript or the Lodash library?

Below is an example of an array of objects I am working with: { countries: [{ "country_alpha2_code": "PW", "country_name": "PALAU" },{ "country_alpha2_code": "US&qu ...

In a situation where Typescript fails to provide enforcement, how can you effectively indicate that a function is not defined for specific value(s)?

If I were to utilize Typescript to create a function called mean that calculates the mean of an array of numbers, how should I handle the scenario where the array is empty? Enforcing that an array must be non-empty can be inconvenient, so what would be th ...

Delete some words from the phrase

Within my programming, I am utilizing an Azure Function to retrieve data from AzureSQL. The returned string in a specific column appears as follows -> Word, a. s.\1002: SomeWord\7010: AnotherWord\7300: AnotherOneWord\7304: LastWord. ...

Working with e.charcode in TypeScript allows for easy access to

I'm having trouble understanding why this code snippet is not functioning as expected. const addRate = (e: { charCode: KeyboardEvent }) => { if (e.charCode >= 48) { ... } } The error message I receive states: 'Operator '>=& ...

Incorporate the username of the logged-in user into the navbar within Angular 5

I need help figuring out how to retrieve the username from the login view/component in Angular and display it in the navbar consistently. I believe I need to use services/observables, but as a beginner, I'm not sure where or how to start. Any guidance ...

Why is it that the Jasmine test is unsuccessful even though the 'expected' and 'toBe' strings appear to be identical?

I have been developing a web application using Angular (version 2.4.0) and TypeScript. The application utilizes a custom currency pipe, which leverages Angular's built-in CurrencyPipe to format currency strings for both the 'en-CA' and &apos ...

Input for Shared Component with routerLink

I'm looking to develop a shared component featuring a button that, upon clicking, redirects the user to a specified location. I want the consumer of the component to be able to define the route. How can I make this happen? My current idea is to set t ...

Unable to convert JSON data for integration with rxjs

I am currently using a webSocket to receive data from my server. I have created an rx Subject called MessageEvent that allows me to retrieve the data. However, although I can successfully log the JSON data in my observable, I am unable to access any prope ...

Attempting to verify if a function is being invoked within a subscription, but finding that it never gets activated

I have a method that needs to be tested when called in an ngOnInit. Specifically, I want to ensure that when the ngOnInit is triggered, this.anotherService.methodToCall() is executed and verify what parameters it is called with. However, despite my effort ...

Filtering nested arrays within an array with a condition object in typescript

My object array (in Json format) looks like this: var datas = [ { "Id": "1", // Includes 10 fields "tests": [ { "id":"1-1", "isSelected": true, }, { "id":"1- ...

Swapping out the standard if/else logic for try/catch error

I'm facing a challenge in removing the then statements from this code snippet and replacing all catches with try/catch statements. I'm struggling to figure out how to handle the then statements. export class WelcomePageContribution implements IW ...

To avoid TS2556 error in TypeScript, make sure that a spread argument is either in a tuple type or is passed to a rest parameter, especially when using

So I'm working with this function: export default function getObjectFromTwoArrays(keyArr: Array<any>, valueArr: Array<any>) { // Beginning point: // [key1,key2,key3], // [value1,value2,value3] // // End point: { // key1: val ...

Angular Material's *matNoDataRow directive is malfunctioning

I am having an issue with using the *matNoDataRow directive in Angular Material. I have created a MatTable with filtering functionality, and when no data matches the filter, I want to display a specific text. However, the directive does not seem to be work ...

Angular 2 Issue: @Input() Directive Not Recognized - Unresolved Reference Error

I am a beginner trying to grasp Angular2 concepts from ng-book 2(v49). Below is the code snippet from article.componenets.ts file: import { Component, OnInit } from '@angular/core'; import { Article } from './article.model'; @Componen ...

The page-router-outlet feature, aptly named, places a striking blue header at the top of

I am currently working with NativeScript and Angular to implement tabs in my application. Everything is functioning well, but I am seeing a blue line with the word 'client' displayed at the top of the app. This seems to be coming from the page-ro ...

What is the method for retrieving array values from an attribute?

I am currently developing an Angular 6 application and I need to pass and retrieve array values dynamically through attributes. Here is the code snippet I have used for this purpose: HTML: <ul class="list-unstyled" id="list" [attr.parent_id]="123"> ...

When trying to style a Material UI component in Mui v5, no matches for overloads were found

In my attempt to enhance the style of a Material UI Component (TextField) shown in the image, I encountered an error that seems to persist no matter what troubleshooting steps I take. Interestingly enough, I never faced such issues when working with styled ...

The json-server-auth feature is failing to function properly upon initialization

I recently attempted to use json-server-auth by installing it via npm, but encountered a problem when trying to start it. The error message I received is as follows: json-server-auth : The term 'json-server-auth' is not recognized as the name ...