Stopping observers in Observable.merge can be achieved by unsubscribing from the merged

In my code, I have a method that sets up a timer:

 create(options: any) {
    return timer(0, 1000).pipe(
      map(() => {
        return options;
      }),
      takeWhile(() => new Date() < options.finishDate)
    );
  }

After creating the timer, it is added to an array called this.timers of Observables:

this.timers.push(this.create({finishDate: new Date()}))

When I merge these observers together:

this.mergeObserver = Observable.merge(this.timers).subscribe(x => {
   console.log(x);
});

Even after the timer has finished, I notice that console.log(x); still continues to output values.

Why does this happen? And how can I stop all timers in the array?

I attempted to unsubscribe from the timers like this:

 Observable.merge(this.timers).subscribe(x => {
   x.unsubscribe();
});

However, this method did not successfully stop the Observable.merge.

Answer №1

this.mergeObserver = Observable.merge(this.timers).subscribe(x => {
   console.log(x);
});

Here, the mergeObserver variable is not an observable but a subscription. The subscribe method actually returns a subscription object. Therefore, renaming it to mergeSubscription and then calling unsubscribe on this object is the correct way to unsubscribe.

If you wish to have a reference to the observable itself, you need to subscribe after obtaining the reference as shown below:


this.mergeObserver = Observable.merge(this.timers);

this.mergeSubscription = this.mergeObserver.subscribe(x => {
   console.log(x);
});

To unsubscribe, you can use the mergeSubscription object like this:


Observable.merge(this.timers).subscribe(x => {
   x.unsubscribe();
});

It's important to note that in the above code snippet, you cannot call `unsubscribe` directly on `x` because `x` represents the value emitted by the merged timers. When one of the timers emits, the merge operation will emit that value as well, which is just a number and doesn't have an `unsubscribe` method.

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

JavaScript for Acrobat

I am currently creating a form in Adobe Acrobat and incorporating additional functionality using JavaScript. I have been searching for information on the control classes for the form, such as the member variables of a CheckBox, but haven't found any c ...

The Selenium driver's execute_script method yields no result

One of the tasks I have is to determine if a specific element is within view. If it is, I want the script to return True; otherwise, False: driver.execute_script('window.pageYOffset + document.querySelector(arguments[0]).getBoundingClientRect().bottom ...

Angular - Highlight a section of a string variable

Is there a way to apply bold formatting to part of a string assigned to a variable? I attempted the following: boldTxt = 'bold' message = 'this text should be ' + this.boldTxt.toUpperCase().bold() ; However, the HTML output is: thi ...

Detecting Unflushed Requests in Jasmine and AngularJS

I'm encountering some issues passing certain tests after implementing $httpBackend.verifyNoOustandingRequest(). Interestingly, excluding this from my afterEach function allows the tests to pass successfully. However, including it causes all tests to ...

Unable to navigate through information received from API

I need assistance in mapping the API data. Can you provide guidance? https://i.sstatic.net/wlYH6.png https://i.sstatic.net/TW7hv.png https://i.sstatic.net/3aZGz.png ...

Swiper: What methods can be used to classify the nature of an event?

Currently, I am utilizing Swiper for React in my project. I find myself in need of implementing a different effect when the user swipes versus using buttons to switch between active slides. Upon examining the swipe object for pertinent details regarding ...

Dynamic rendering of components in React can be achieved by passing arguments to functions

In my single-page application (SPA), I have multiple sections (Components) that I want to toggle based on a cookie. My idea is to create a function that can switch between two different components by passing their names as arguments. My proposed approach: ...

Include and remove JSON data items within ng-repeat loop

I am in the process of creating a dynamic page where users can add multiple locations to their contact information. Currently, my code looks like this: <div class="input-append" ng-repeat="location in newPartner.partner_location"> <input clas ...

What could be causing the screen to scroll when typing in a textarea on Firefox?

Encountering a strange issue with the isotope plugin, specifically in Firefox. Each isotope element contains a textarea, and when I scroll down to the bottom and start typing in one of the textareas, the screen unexpectedly jumps to the top. I have recreat ...

Creating an associative array in Javascript by utilizing a for loop

I am attempting to create an array called userRow{} by using: $('#divResults tr').find('td:nth-child(2)').text(); This will fetch 12 first names from a column in an HTML table, such as John, Dave, and so on. $('#divResults tr&ap ...

How to correctly pass values in AngularJS functions

Here is a function that takes a description variable as a parameter $scope.relsingle = function(description) { console.log(description); var url = $scope.url+'/api/descrelation?limit=4&description='+description; $http.get(url).su ...

The process of transferring information from a JSON API to TypeScript models

When working with my JSON API in my services, I need to pass the data to my models. What is the most efficient way to accomplish this task? Currently, I am following this process: import { Attachment } from '.'; export class Contact { id: nu ...

methods for performing multiplication on dynamically inserted variables using jquery

I'm trying to dynamically calculate the total amount based on the price and product quantity after changing the value in the #quantity text-box. I implemented the following solution, but upon checking the Firefox console, I noticed that there is no ca ...

Did you manage to discover a foolproof method for the `filesystem:` URL protocol?

The article on hacks.mozilla.com discussing the FileSystem API highlights an interesting capability not previously mentioned. The specification introduces a new filesystem: URL scheme, enabling the loading of file contents stored using the FileSystem API. ...

Lerna: The Ultimate Guide to Installing External Packages Across Multiple Projects

We utilize Lerna for managing our mono-repo projects, and I am seeking the most effective method to install an external package in my projects while ensuring they all use the same version. Here is my project structure (my-Main-A and my my-Main-B both depe ...

Unable to retrieve nested object from an immutable object

How can I access an Array in an object? I want to display the entire list. render() { var elems = this.props.items.course_list; console.log(elems); return ( <div> </div> ) } Here is a visual representation: htt ...

Unable to execute multiple queries within a CloudCode query

In my quest to discover new users who I have not connected with before using a cloud function, I am utilizing several tables: Users table - This standard table includes an additional "hasLight" boolean column Connected table: 'user' - a point ...

Unable to patiently wait for Axios to be called multiple times

I'm encountering an issue with making consecutive axios API calls in my code. I expected that since each call was awaited, they would be treated the same way. However, when I execute the code, I receive the error message: TypeError: parsedEmp is not i ...

Converting data from an HTML file to JSON with the help of <input file> feature in Javascript (Vue)

Currently, I am attempting to upload an HTM file using in Vue. Within this file, there is a styled table utilizing , and other HTML elements... I am curious, is it feasible to extract the tabulated data from the HTM file and convert it into another forma ...

I am attempting to push notifications to a particular device using Firebase cloud functions

I am currently developing a chat app using Flutter, and I am attempting to send notifications to specific devices using a cloud function. The goal is for a user to send a message to a friend and have the friend receive a notification with the message. Howe ...