Merging arrays from observables without the need to wait for all of them to finish

Within my application, I have established a process where data is fetched from a remote server at regular intervals. The retrieved data is structured as an array of objects and is then showcased in the HTML template using the angular async pipe.
To enable caching functionality, I am utilizing shareReplay():

  private refresherToggleSales$: Subject<void>;
  private displayLastSales$: Observable<Sale[]>;

  public InjectSale$: Subject<Sale[]>;
  
  [...]

   get LastSales() : Observable<Sale[]> {
    if (!this.displayLastSales$) {
      const rTimer$ = timer(0, DefaultRefresh);

      this.displayLastSales$ = rTimer$.pipe(
        switchMap(_ => this.getLastSales()),
        shareReplay(this.CACHE_SIZE),
        takeUntil(this.refresherToggleSales$)
      );
    }

    return merge(this.displayLastSales$, this.InjectSale$);
  }

  private getLastSales() : Observable<Sale[]> {
    // logic to fetch data from server
  }

Whenever there is a manual input of sale data within the application, the aim is to display it promptly without waiting for server updates.

If InjectLastSale$.next() is called with a 1-element array, it replaces all existing data entirely.
How can both streams be merged without one being dependent on the other's completion?

Answer №1

You're getting warmer! Consider adjusting the placement of your merge function.

get LastSales() : Observable<Sale[]> {
    
  if (!this.displayLastSales$) {
    this.displayLastSales$ = timer(0, DefaultRefresh).pipe(
      switchMap(_ => this.getLastSales().pipe(
        mergeWith(this.InjectSale$),
        scan((acc, vals) => [...vals, ...acc], <Sale[]>[])
      )),
      shareReplay(this.CACHE_SIZE),
      takeUntil(this.refresherToggleSales$)
    );
  }

  return this.displayLastSales$;
}

Answer №2

Utilize the combineLatest Operator

combineLatest(this.displayLastSales$, this.InjectSale$).subscribe(
(displayLastSales, InjectSale) => {
        console.log(displayLastSales, InjectSale )
      })

Now, you can observe emitted data immediately without having to wait for the other observable to emit data.

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

Exploring the zoom functionality and tooltip features of Area Range charts in Highcharts

I need help with a couple of things on the high charts area range chart: I am trying to enable zooming into the y-axis of the chart, but I am facing difficulties. Can anyone suggest how this can be achieved? Below is the link to my jsfiddle with the sam ...

Utilizing a Typescript class interface does not maintain the original method types

Struggling to define a Typescript interface and implement it in a class. The issue lies in the method signatures of the interface not being applied to the class as expected. Below is a simplified example: export interface Foo { bar(value: string): voi ...

To activate the ion-toggle, simply click on the ion-label

Currently, I am in the process of developing a page using Ionic 5. One of the features I am including is a 'remember me' button which utilizes <ion-toggle>. <ion-item> <ion-label>remember me</ion-label> <ion-to ...

What is the method for obtaining the number of weeks since the epoch? Is it possible to

Currently, I am setting up a DynamoDb store for weekly reporting. My idea is to use the week number since 1970 as a unique identifier for each report record, similar to epoch milliseconds. Here are some questions I have: How can I determine the current w ...

What is the best way to access data from a local JSON file in Gatsby when using TypeScript and GraphQL?

I'm updating my former gatsby site using TypeScript. I encountered an issue while trying to retrieve data from a local JSON file: There appears to be an error in your GraphQL query: Cannot find field "allNavigationLinksJson" on type "Q ...

Incompatibility issue between metadata versions for Angular 4 and @ng-bootstrap libraries

I've been working with the Angular bootstrap module and encountered an issue. After installing the module using the command npm install --save @ng-bootstrap/ng-bootstrap and importing it into the main app module, I attempted to re-run the application ...

Error: An unexpected closing tag "<p>" was encountered while parsing the template

I am facing an issue while trying to format an XML file in Angular. Here is the code snippet I attempted to use: <div class="element-box"> <div class="details-wrapper"> <p><b class="label">Raw Request</b> <pre& ...

Having trouble getting Angular ngIf to work with multiple matches?

I am facing an issue with my ngIf directive that has got me puzzled. Initially, my ngIf statement was functioning flawlessly like this. ngIf="this.offerFormGroup.get('identityTypeId').value == 4 However, now I need to extend it by adding mo ...

Error: Unable to load chunk.js in Angular 7

After upgrading to Angular 7, I've been diving into the world of Lazy loaded modules. However, despite my efforts, I can't seem to find #chunk.js anywhere in the network tab when I click on components within the lazy loaded module. Even when Con ...

Optimizing Angular: Configuring baseHref for assets during development with SSR

During production, we set the base href using the following command: ng build --base-href /app/ This configuration works smoothly as our assets are also accessible at /app/assets/, just as expected. However, I have been facing difficulties achieving the ...

Error in Angular 12: Highcharts - Point type does not have property value

When working with Highcharts in Angular, I encountered an issue in Angular 12 where the error "Property value does not exist on type Point" appeared under legend parameters. Everything else seems to be functioning correctly, but I am unsure where to place ...

Connecting attribute in Angular 5 through @Input

(UPDATED) I originally had a basic jarallax setup with just a div containing the corresponding configuration in a component: <div class="view cover-jarallax" data-jarallax="{"speed": '0.w'}" style="background-image: url(imgurl);' + &apo ...

When trying to pass props into setup using VueJS 3 Composition API and TypeScript, an error may occur stating: "Property 'user' does not exist on type"

I need help figuring out why TypeScript is not recognizing that props.user is of type UserInterface. Any advice or guidance would be greatly appreciated. You can reach me at [email protected], [email protected], [email protected]. This seem ...

Is there a way to use Regex to strip the Authorization header from the logging output

After a recent discovery, I have come to realize that we are inadvertently logging the Authorization headers in our production log drain. Here is an example of what the output looks like: {"response":{"status":"rejected",&quo ...

Exploring the Contrast: Library vs. Framework within Angular Material and Bootstrap

I'm struggling to grasp the concept of why Angular Material is classified as a library, while Bootstrap is considered a framework. What sets them apart in terms of categorization? Can you help shed some light on this distinction? ...

The source code in VS Code was not accurately linked

I'm currently facing an issue with running my angular2 project from vs code. Below are the contents of my tsconfig and launch.json files. tsconfig.json { "compilerOptions": { "declaration": false, "emitDecoratorMetadata": true, "experi ...

AsyncPipe encounters an InvalidPipeArgument, signaling a pipe error

I've been exploring Async Pipe and seem to be stuck at this particular point... import { Component, OnDestroy } from '@angular/core'; import { AngularFireDatabase } from 'angularfire2/database'; @Component({ selector: 'a ...

What is the best way to transfer a Blob image from Angular2 to NodeJs?

Encountering difficulties while attempting to upload a photo from the frontend. There is an input file where a file can be selected from the computer. The goal is to send that photo to the backend and store it as a Blob. Initially trying to retrieve the ...

Is there a way to determine if a route, or any of its nested routes, are currently active

Consider the following route examples: <Routes> <Route path="admin"> <Route path="users"> <Route index element={<UserList />} /> <Route path="create" element={<UserDetails ...

Trouble with displaying IonicV4 Menu Component in Split Pane

Currently, I am in the process of developing an app using Ionic V4. Despite following the documentation provided by Ionic, even the simplest tasks are proving to be quite challenging for me. My goal is to display a split pane with a side menu. The side me ...