Remove all subscribers from the Observable

I'm relatively new to using Observables and Typescript, so bear with me if this question sounds like a beginner one. I am trying to create a simple timer but I want the ability to unsubscribe all subscribers from within the timer itself.

Here is what my current code looks like:

import { Observable } from "rxjs/Rx";

export class Timer {

    private interval: number;
    private ticker: Observable<any>;

    constructor() {
        this.interval = 1000; // Miliseconds
        this.ticker = Observable.interval(this.interval).timeInterval();
    }

    complete() {
        // Unsubscribe all listeners here
    }
}

Any ideas on how I can achieve unsubscribing all listeners from the complete method?

Answer №1

If you find yourself without the Subscription objects of observers, it's impossible to directly unsubscribe them.

However, an alternative approach is available by utilizing the takeUntil operator to finish the source Observable and consequently dispose of the chain along with unsubscribing all observers.

constructor() {
  this.end = new Subject();

  this.ticker = Observable.interval(this.interval)
    .takeUntil(this.end)
    .timeInterval();
}

...

complete() {
  this.end.next();
}

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 way in React to specify which properties to pass (and when to pass them) to child components based on the properties of the parent component?

In this hypothetical scenario, there are 4 components already in place: MainComponent1, MainComponent2, IntermediateComponent, and ChildComponent. Both MainComponent1 and MainComponent2 can utilize IntermediateComponent as their child component, while Chil ...

Guide to forwarding a visitor from an outdated URL to a fresh one, complete with slug using Next.js redirect 301

I made a change to the URL of one of my subpages that is already live. The old link is no longer supported, but it is still present in many places. Instead of updating all instances of the old link, I would like to set up a redirect from the old URL to the ...

The directive attribute in AngularJS fails to connect to the directive scope

I have been attempting to pass an argument to a directive through element attributes as shown in the snippet below: directive app.directive('bgFluct', function(){ var _ = {}; _.scope = { data: "@ngData" } _.link = function(scope, el ...

Here is an example of how to use a script tag to check the value of a select tag in HTML:

Hi there! I'm working on a piece of code where I need to retrieve the selected value from a dropdown menu in an HTML select tag and display it in the element with the id='h1' at the bottom. The script tag is already included within the head ...

Unable to dynamically display an HTML5 video using JavaScript

I'm facing an issue with displaying videos in a modal dynamically. Here's the scenario: +------------+---------+ | Name | View | +------------+---------+ | 1.mp4 | X | | 2.mp4 | X | +------------+---------+ The X ...

Is there a way for the React select component to adjust its width automatically based on the label size?

After defining a React select component, it looks like this: <FormControl> <InputLabel id="demo-simple-select-label">Age</InputLabel> <Select labelId="demo-simple-select-label" id=&quo ...

React has successfully installed react router, but unfortunately, I am encountering difficulty in getting the page

I'm currently in the process of setting up react router and I need help rendering the main page. Here is the current configuration in my index.js import React, { Component, PropTypes } from 'react'; import { Router, Route } from 'reac ...

creating a loop to handle AJAX requests for JSON data

My JSON call successfully loads the data.root.offer[0].region data into a div with the class .region. Here is the code snippet: $.getJSON('json/data.json', function(data) { $('.region').html('<p>' + data.root.offer[0] ...

Is there a way to call class methods from external code?

I am seeking clarification on Class files. Below is an example of a Class that I have: class CouchController { constructor(couchbase, config) { // You may either pass couchbase and config as params, or import directly into the controller ...

How can I create a rectangular border around text using the HTML5 canvas?

How can I dynamically draw fitted rectangles around text labels (person's full name) without fixed sizes, taking into account that the labels vary in lengths? Below is the code used to draw the text labels: var ctx = document.getElementById('ma ...

Angular 4 scatter chart with multiple data points using Google charts

I'm currently developing a scatter graph in Angular 4 using ng2-google-charts from https://www.npmjs.com/package/ng2-google-charts It seems like this is essentially a wrapper for Google Chart Service. The graph looks great with a few values, but whe ...

Swap the image source with a different image attribute when making the website responsive

I have implemented a custom attribute for the img tag in my code, such as data-tablet and data-mobil <div class="myDiv"> <img src="img-1.jpg" data-tablet="img-2.jpg" data-mobil="img-3.jpg"> </div> My goal is to have the image source c ...

Error message: "Error encountered while building Next.js - ReferenceError: 'describe' is not defined"

I am facing difficulties achieving a successful next build without encountering the following error: > Build error occurred { ReferenceError: describe is not defined Although the dev server and tests execute smoothly, it appears that the jest global d ...

Is it possible to use Vuejs v-model for a complete form instead of individual inputs?

Note: This solution is applicable for Vue 2.X I am currently working on a unique Vue.js component that has the ability to generate "custom" forms. This component essentially functions as a standalone form with multiple input fields. Users have the option ...

Tips for resolving type checking errors in TypeScript and React

I encountered an error and would appreciate any assistance in resolving it. My tech stack consists of react, typescript, and Material UI. I am attempting to customize a button using the following link: https://mui.com/material-ui/customization/how-to-custo ...

Creating a variable name dynamically using Typescript

I am looking to efficiently create multiple instances of variables and assign values in a single statement, an example of which is shown below. this.myList1[data.id] = data.id + "-" + data.desc; this.myList2[data.id] = data.id + "-" + data.desc; this.myLi ...

Leveraging a specific section of an HTML5 CSS3 Bootstrap template in a separate template

As I create my website using a combination of free templates, I often find myself needing to merge elements from different designs. One specific example is wanting to incorporate the "Client Logo Slider" component from template 2 into my original template. ...

JavaScript maintaining records and connections between multiple asynchronous events

I am working on an Angular 10 project where users can compress and upload images to Google Cloud Storage. The compression and uploading functionalities are functional, but I'm facing challenges with managing the asynchronous process of handling multip ...

Using AJAX and FormData to Attach a List upon Submission

I am currently working on connecting a list of "Product Specifications" to my "Add Product" dialog, and I'm using AJAX to submit the form. Since users are able to upload a product image within this form, I am sending the AJAX request with a 'For ...

Verifying the eligibility of a value for a union type

In my app, there is a type called PiiType that enforces strong typing: type PiiType = 'name' | 'address' | 'email'; When receiving potentially sensitive information from the server, we need to verify if it aligns with this d ...