1

Code like this question Performance of using same observable in multiple places in template with async pipe

But doesn't work in rxjs6?

https://stackblitz.com/edit/angular-shared-fail

import { Component, Input } from '@angular/core';
import {Observable, of, range, zip} from 'rxjs';
import {filter, map, share, switchMap, tap, toArray} from 'rxjs/operators';

@Component({
    selector: "some-comp",
    template: `
        Sub1: {{squareData$ | async}}<br>
        Sub2: {{squareData$ | async}}<br>
        Sub3: {{squareData$ | async}}
    `
})
export class HelloComponent {
  squareData$: Observable<string> = range(0, 10).pipe(
    map(x => x * x),
    tap(x => console.log(`CalculationResult: ${x}`)),
    toArray(),
    map(squares => squares.join(', ')),
    share()  // remove this line and the console will log every result 3 times instead of 1
  );
}

Every number log 3 times. Expected once.

wgf4242
  • 775
  • 2
  • 11
  • 23

1 Answers1

1

You're piping the observable three times hence the three printouts. Let your HomeComponent template be like below and you'll see the desired output.

  <div *ngIf="(squareData$ | async) as squares">
    Sub1: {{squares}} <br/>
    Sub2: {{squares}} <br/>
    Sub3: {{squares}}
  </div>
ChiefTwoPencils
  • 13,548
  • 8
  • 49
  • 75