Purge stored events from BehaviorSubject in Angular2 using Observables as they are consumed

I'm encountering an issue that I believe stems from my limited understanding of Observables.

This project is built on Angular2 (v4.0.3) and employs rx/js along with Observables.

Within a state service, there exists a store for events:

  // Observable string sources
  private currentEventStore = new BehaviorSubject<string>("");

  // Observable string streams
  public currentEvent$ = this.currentEventStore.asObservable();

  // Service message commands
  setCurrentEvent(nextEvent: string) {
    this.currentEventStore.next(nextEvent);
  }

In my components, I subscribe to currentEvent$ to listen for events and act accordingly.

this.stateSvc.currentEvent$
  .subscribe(
  currentEvent => {
    this.currentEvent = currentEvent;
    if (currentEvent != '') {
      this.handleCurrentEvent(currentEvent);
    }
  });

The issue arises when the store accumulates all events and returns them each time. So, upon triggering a 'create' event, my function creates a record - which works fine initially. However, with subsequent 'create' events, the function picks up multiple events, leading to multiple records being created. This pattern continues with each successive event.

My goal is to have the stream flush out old events so that the currentEvent$ store only retains unaddressed events.

Is there a way to flush the store? Am I overlooking something in my expectations and implementation?

Answer №1

After struggling with a problem for days, I finally cracked it shortly after posting a question.

The root of the issue lies in the fact that each time I revisit the component responsible for registering subscribers, another subscriber is added to the observable. This means that on subsequent visits, multiple subscribers are firing, causing the event to be handled multiple times. If I return once more, the number of subscribers continues to grow, leading to even more instances of the event being handled.

To resolve this, I realized that I needed to adjust my subscription process by assigning them to a variable and unsubscribing when the component is destroyed.

Therefore, the subscribe method should be structured as follows (highlighting the usage of 'this.observeEvent ='):

this.observeEvent = this.stateSvc.currentEvent$
  .subscribe(
  currentEvent => {
    this.currentEvent = currentEvent;
    if (currentEvent != '') {
      this.handleCurrentEvent(currentEvent);
    }
  });

In addition to this, the following code should be included in the component:

ngOnDestroy() {
  this.observeEvent.unsubscribe();
}

This action ensures that the subscribers are properly unregistered, preventing them from accumulating each time the component is loaded.

Prior to this breakthrough, I had attempted to solve the problem without success. However, once I started using an instance variable to store the Observable, everything fell into place.

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

Understanding Arrays in Angular JSIn this article, we

I am new to working with Angular JS. Currently, I am populating an array and attempting to showcase its contents on the HTML page using ng-repeat. $scope.groupedMedia = []; // Elements are being added through a for loop. $scope.groupedMedia[year].push(r ...

Tap here to switch between 2 jquery functions

Due to the deprecation of the toggle() method in jQuery version 1.8 and its removal in version 1.9, an alternative approach is needed for versions 1.11 and above. You can check out the documentation for more information. If you are looking to replicate th ...

having difficulty altering a string in EJS

After passing a JSON string to my EJS page, I noticed that it displays the string with inverted commas. To resolve this issue, I am looking for a way to eliminate the inverted comma's and convert the string to UPPERCASE. Does anyone know how to achiev ...

Are you harnessing the power of ng-view for your highly dynamic content?

I'm currently in the process of developing a website that offers users the ability to search for various products, such as laptops. Below is the code snippet from my main index div: <div class="content" id="main"> <div id="search-wrap" ...

Choose the parent element along with its sibling elements

How can I target not only an element's siblings but also its parent itself? The .parent().siblings() method does not include the original element's parent in the selection. $(this).parent().addClass("active").siblings().removeClass("active"); I ...

Harnessing the Power of Script Loader in Your webpack.config.json File

I'm taking my first steps into the webpack world with Vue.js and vueify for ES6 modules. I've run into a challenge when it comes to loading third-party jQuery plugins. I've successfully used the ProvidePlugin to load jQuery. plugins: [ ...

What is the issue with retrieving HTML from an iframe in Internet Explorer when the contents are

Here is the script I used to generate an iframe: Ifrm = document.createElement("IFRAME"); document.body.appendChild(Ifrm); IfrmBod = $(Ifrm).contents().find('body'); IfrmBod.append('<p>Test</p>'); The jQuery function for a ...

The MongoClient object does not possess the 'open' method

I recently started working on a project using Node.js, Express.js, and MongoDB. I've encountered some issues while trying to set up the database configuration. Below is a snippet of code from my index.js file: var http = require('http'), ...

"An error occurred: Uncaught SyntaxError - The import statement can only be used within a module. Including a TypeScript file into a

I need to integrate an Angular 10 TypeScript service into a jQuery file, but I am facing an issue. When I try to import the TypeScript service file into my jQuery file, I encounter the following error: Uncaught SyntaxError: Cannot use import statement outs ...

Performing AJAX in Rails4 to update boolean values remotely

Suppose I have a model named Post which includes a boolean attribute called active. How can I efficiently modify this attribute to either true or false directly from the list of posts in index.html.erb using link_to or button_to helper along with remote: ...

Is there a way to merge two observables into one observable when returning them?

I'm struggling with getting a function to properly return. There's a condition where I want it to return an Observable, and another condition where I'd like it to return the combined results of two observables. Here is an example. getSearc ...

Ensure that the date range picker consistently shows dates in a sequential order

Currently utilizing the vuetify date range picker component https://i.stack.imgur.com/s5s19.png At this moment, it is showcasing https://i.stack.imgur.com/GgTgP.png I am looking to enforce a specific display format, always showing the lesser date first ...

Exploring the world of chained JavaScript Promises for automatic pagination of an API

Dealing with a paged API that requires fetching each page of results automatically has led me to construct a recursive promise chain. Surprisingly, this approach actually gives me the desired output. As I've tried to wrap my head around it, I've ...

Tips for styling an image and vCard within a Foundation accordion menu

I am working on a project that involves creating a list using an accordion feature to display names of individuals. When a user clicks on a person, I want the dropdown content to show their image and vcard details. How can I structure the content so that ...

What is the best way to simulate calls to specific methods of cordova plugins?

As a newcomer to testing Cordova apps, I'm seeking advice on the best practices for my current situation. Here's the scenario: I have a module factory: angular .module('app.services') .factory('UtilsService', UtilsSer ...

Learn the process of covering the entire screen with a video

I'm attempting to achieve this: IMG Below is the code snippet I've been using: <div class="container" id="containervideo"> <div id="video"> <div class="box iframe-box"> <div class="container"> ...

Send an AJAX request to redirect to a different page on a PHP server

After collecting data from JavaScript, my page transfers it to PHP and then MySQL. The issue arises when I want the page to redirect to different pages based on the database content. I attempted to use the header function, but it only displayed the entire ...

Tips for displaying personalized data with MUI DatePicker

I need to create a React TypeScript component that displays a MUI DatePicker. When a new date is selected, I want a custom component (called <Badge>) to appear in the value field. Previously, I was able to achieve this with MUI Select: return ( ...

Is there a way to receive notifications on an Android device when the real-time data updates through Firebase Cloud Messaging (FC

I am attempting to implement push notifications in an Android device using Firebase Realtime Database. For example, if an installed app is killed or running in the background, and a user posts a message in a group (resulting in a new child being added in t ...

Method in AngularJS Controller Instance

I have a unique angular js controller where I am structuring it for inheritance by other controllers. Rather than defining the function as a single one within the angular's controller function, I am taking a different approach: function SomeCtrl($ ...