What is the best way to update a BehaviorSubject holding an array without replacing the entire array?

When it comes to adding items to an array BehaviorSubject, the common practice is to assign a copy of the entire array along with the new item using next().

However, I am looking for a way to push items into this array without having to assign a full copy, especially since I have other array operations to perform that are complex with BehaviorSubject.

Is there a method to achieve this without the need for copying the entire array, or is there an alternative to BehaviorSubject that could simplify this process? Additionally, are there any useful libraries that can assist with this?

For example:

export class ArrayService {
  currentArray = new BehaviorSubject<[]>([]);

  addItem(){
    let newItem = 'newItem';
    currentArray.next([...this.currentArray.getValue(), newItem]);
  }
}

Answer №1

Create a brand new array, add elements to it, and then trigger it.

export class ArrayManager {
  allElements = [];
  allElements$ = new BehaviorSubject<[]>(this.allElements);

  addElement(){
    let newElement = 'newElement';
    this.allElements.push(newElement);
    this.allElements$.next(this.allElements);
  }
}

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

Problem encountered with a selection menu

I'm experiencing some trouble with the dropdown menu. Whenever I try to move the mouse to access the dropdown menu, it seems unresponsive. I attempted adjusting the padding on a line of code but ended up moving the entire line instead. Here is the cod ...

Instructions on setting div opacity when Overflow is set to visibleExplanation on setting opacity for div with Overflow

In my HTML code, I have a div element and an image tag stacked one on top of the other. The div is smaller than the image. I have set the overflow property to visible for the div. My query is, when I add an image to the image tag, the content that overflow ...

Trouble with Ajax transmitting multiple PHP variables

I am attempting to utilize an ajax request to visit a URL with two parameters. Unfortunately, my current script is not displaying any response. $(document).ready(function(){ $("#ocountClc").click(function (){ $.ajax({ type: "POST", url: "h ...

Issue with Ajax reload functions malfunctioning

Embarking on a new journey, I am diving headfirst into the world of web development. As an artist and writer, I have recently delved into the realm of creating a project that integrates a cms, project manager, and database front-end using php, mysql, and j ...

Is it possible to add a vertical scrollbar to the vertical navigation pills on a Bootstrap

Is it possible to create a vertical scroll bar for my nav pills when they exceed the screen size? /* * * ========================================== * CUSTOM UTIL CLASSES * ========================================== */ .nav-pills-custom .nav-link { c ...

Explore a nested array of objects to identify and retrieve the complete pathway for every matching item

Looking for a solution to search through a deeply nested array of objects and retrieve the paths of all matching objects? While I have made progress on the problem, the current code only returns the path of the first matched object. Take a look at the inpu ...

Enabling a checkbox grid for exclusive rectangular selections

Apologies for the confusing title, I struggled to come up with something more fitting. Let's say my client needs a square area on their homepage where they can upload images that will be placed within various boxes in a grid. The available box optio ...

The sendFile function fails to transmit any data

Currently working on integrating the mailChimp API into my project, but facing an issue with the resFile code that handles sending the success response. The current code snippet: async function run(){ try { const res = await mailch ...

Insert a fresh element above the existing elements fetched from the API

My application consists of two components: add-product.component and show-list.component. The show-list component displays a list obtained from the list-product API, which requires 3 parameters in the body (user_id, session_key, page). The third parameter ...

Revert animation back to its initial position with the help of JavaScript

After implementing the script below, I successfully managed to shift my image to the right upon clicking: <script> var myTimer = null; function move(){ document.getElementById("fish").style.left = parseInt(document.getElementById("fish ...

Collapse in Bootstrap 3 Navigation Bar

I'm really struggling to understand why my navbar is refusing to collapse. I've included the necessary Bootstrap CSS and JS files, as well as the transition and collapse JS files. Below is the code that I've been working with. Any assistance ...

Implement a dynamic table in real-time with jQuery AJAX by fetching data from JSON or HTML files

Hey @SOF, I'm trying to add an auto-update feature to my school grades webpage using jquery and ajax to refresh the data when new information is available. I also want to create a "single view" for classes. The challenge I'm facing is getting t ...

Separate each element with a time gap when using the .each() function in

Below is the code snippet that I have: $('.action-button').each(function(i, obj) { $(obj).trigger('click') }); I am looking to introduce a delay between each iteration of the loop, ideally a 5-second delay. Is it achievable through se ...

Dynamic routing with ngIf in Angular 2's router system

Is there a way to use *ngIf with dynamic router in Angular? Let's say I have a top navigation component with a back button, and I only want the back button to be visible on the route 'item/:id'. I tried using *ngIf="router.url == '/ite ...

JWT authentication for restricted routes

I'm currently developing an application that requires users to log in and allows them to join private groups. I have successfully implemented the login part using JWT, but I'm struggling with how to prevent users from joining private groups until ...

Experience the magic of TypeScript combined with the power of the ...rest operator, paired with the functionalities of Pick

I am looking to define the Props type for a React component in a way that includes all the properties of the underlying "core" HTML element it renders, but still allows for my component to override certain props. Here is an example in picture/code form: h ...

Confusion surrounding asynchronous functions in Node.js

When handling routes or endpoints with multiple operations, I often encounter scenarios where I need to perform additional actions. For instance, when deleting an item, it's necessary to also remove the related file from S3 along with deleting the col ...

Experimenting with parallelism using TypeScript/JS

Currently, I am tackling a TS project that involves testing concurrent code and its interactions with a database, specifically focusing on idepotency. My goal is to ensure that multiple requests modifying the same resource will either apply changes correct ...

Failure in SystemJS during ahead-of-time compilation due to missing NgZone provider

Previously, I have successfully used Angular's ahead-of-time compilation. However, after adding routing and lazy loading to my app, I am facing difficulties in making it work again. Upon updating my code to the latest 2.0 release, it functions well w ...

"Commitment made ahead of time without allowing for the outcome to

I'm completely new to working with promises and I'm encountering some unexpected behavior in my code. The issue lies in the TaskRunner.SyncObjects function within Main.js, which should be waiting for the selectedCourses variable to be populated ...