Instead of overwriting them, RxJS Observables continue to add newly emitted values onto existing ones

My goal is to create an Observable that dynamically adds more data every time a new event occurs. Let's consider the following scenario:

Imagine we have an elementsService with a method getElements(pageNo: number) that makes an http call to fetch some elements.

  1. When the page loads, we want an observable to fetch the initial page of elements.
@Component({
  template: '<div>{{ elements$ | async }}</div>'
})
export class MyComponent {
  page: BehaviorSubject<number> = new BehaviorSubject(0);
  elements$: Observable<any> = this.page.pipe(
    mergeMap((page) => _service.getElements(page))
  );

  constructor(private _service: Service) {}
  // ...
}

Let's assume the initial result is elements = [ e1, e2 ]

  1. As time passes, a new page event will be triggered
export class MyComponent {
  // ...
  onPageChange(pageNo: number): void {
    this.page.next(pageNo);
  }
}

The next page will return elements = [ e3, e4 ], meaning that the original values e1 and e2 are replaced. How can I modify this so that the new elements e3 and e4 are added to the existing Observable result instead of replacing them?

Answer №1

If you want to accumulate results, you can utilize the scan operator in the following manner:

  items$: Observable<any> = this.page.pipe(
    mergeMap((page) => _service.getItems(page)),
    scan((accumulatedItems, incomingItems) => accumulatedItems.concat(incomingItems), [])
  );

When an emission is received by scan, it will execute the function and emit the resulting value.

(accumulatedItems, incomingItems) => accumulatedItems.concat(incomingItems)
  • The incomingItems represent the new data received from the _service.getItems() call.

  • The accumulatedItems refer to the previously calculated value or the initial "seed value" during the first run.

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 implementing a TypeScript interface, there is no method parameter checking performed

interface IConverter { convert(value: number): string } class Converter implements IConverter { convert(): string { // no error? return ''; } } const v1: IConverter = new Converter(); const v2: Converter = new Converter(); ...

Refresh the Ionic 5 page for optimal performance

In my Ionic single page web app, users input information and create dynamic components like columns and cards. I'm trying to figure out how to completely reload the page back to its initial state after a button is clicked. I've experimented with ...

Angular Material floating labels vanishing or being truncated when hovered over

The behavior of floating labels seems to be causing issues for me. When I hover over them, the label either disappears completely, gets cut off at the bottom, or at times even at the top. I've tried adjusting z-index and overflow visibility within the ...

The requested property 'x' is not found in the object type '{}' but is necessary in the 'Pick<Interface, "x">' type. TS2741

My challenge involves passing data from a redux store to a component using the connect function. Below is the code snippet I am working with: Parent Component: export const MainPage = ( { count, handleIncrementClick, selectedOfferId, }: Ma ...

Are SCSS style sheets being properly included in ng-packagr packaging?

I've been working on developing an Angular component library, packaging the modules for easy NPM installation. However, I took the old-school approach instead of using the CLI like Angular 6 recommends. Despite that, my components function properly wh ...

Ensure that the input focus is consistently set within the ng-template

When I click on a button in my app, an input element becomes visible. Then, when I click on another button, it gets hidden again. I achieved this functionality using a simple ng-template. However, I encountered a problem - I want the input to automatically ...

"Activate the mat-checkbox based on the outcome of a certain process

I'm working with a mat-checkbox that triggers a mat-dialog when clicked. If the user clicks "confirm" in the dialog, I want the checkbox to be checked. If they click "cancel", I want it to remain unchecked. How can I achieve this? Below is the method ...

Angular 8 date validation for start date and end date on a mat-date-picker

My current task involves working with the Mat date picker, specifically focusing on setting up validation rules for start and end dates. One important rule to note is that the end date should always be after or equal to the start date. For instance: If th ...

Encountering an error in Angular 10/11 when integrating ngx-sharebuttons: "The import of 'ɵɵFactoryTarget' (alias 'i0') from '@angular/core' was not found."

As I work on enhancing my angular app, I am looking to incorporate social media share buttons. I came across ngx-sharebuttons, which seems to offer the functionality I desire. However, I am facing issues while trying to build my angular application using ...

Rearrange the layout by dragging and dropping images to switch their places

I've been working on implementing a photo uploader that requires the order of photos to be maintained. In order to achieve this, I have attempted to incorporate a drag and drop feature to swap their positions. However, I am encountering an issue where ...

Is there a way to align cards to stack on both the right and left sides of each other?

I need to create a card that includes text and an image, save it as a component, and then display this component three times in app.component.html so that the cards are all visible on the website. Currently, the cards are stacked vertically. How can I alig ...

Firebase Functions Project encountering a "Cannot find module" error in VS Code

While working on a firebase functions project in Visual Studio Code, I encountered an issue inside the index.ts file. The imported modules were not being recognized even though autocomplete showed that the modules exist. When attempting to import them, I k ...

Edge is experiencing a slowdown when utilizing ng-bind-html

I've been using ng-bind-html to bind HTML content to a div element. However, when I attempt to bind larger amounts of HTML, it can take around 5-6 seconds for the content to load. Interestingly, this issue seems to only occur in Chrome browser. I have ...

The term "containerName" in SymbolInformation is utilized to represent the hierarchy of

In my quest to make the code outline feature work for a custom language, I have made progress in generating symbols and displaying functions in the outline view. However, my next challenge is to display variables under the respective function in the outlin ...

Identifying the origin of the error (whether it's from the client or the server) within

I am utilizing ngrx effect for handling user login in my application: @Effect() authLogin = this.actions$.pipe( ofType(LOGIN_START), switchMap(() => this.http.post('/user/login') .pipe( catchError( (response) => ...

Are there problems with the response values of functions that can handle varying object interfaces?

Currently in the process of developing a command line blackjack app with Node and Typescript, even though I am relatively new to Typescript. My main challenge lies in implementing interfaces for player and dealer objects, as well as creating functions that ...

Inject a new observable into the current Subject

Having an Angular Subject named event$, I want to attach DOM controls as emitters to this observable when screens are loaded. The observable already has subscribers, so I am using a method to merge another observable with it, as shown below (Subscription m ...

Tips for duplicating chosen documents utilizing AngularCLI in conjunction with WebPack for the production build

I am facing an issue with my Angular2 app when building it for production using Angular CLI and WebPack. In order to deploy the app to our production server (IIS), I need to copy certain files to the dist folder. Specifically, I require the web.config and ...

Circular dependency in Angular between two services

BarService cannot be resolved because it depends on FooService, which in turn depends on BarService. Outcome when injecting both services in constructors: Uncaught Error: Can't resolve all parameters for BarService ...

Maintaining type information while iterating over an object with Typescript

I am faced with the challenge of wrapping functions within an object in order to use their return values, all without altering their signature or losing type information. // An object containing various functions const functions = { foo, bar, baz } // Exa ...