1
votes

I have an observable which is merged from two observables. I am using this observable to pass it through the async pipe to a child component. When the two inner observables emit, the last emitted values are being overridden by the newer values.

let a = new Subject();
let b = new Subject();
this.loaderData$ = merge(a.asObservable(), b.asObservable())
setTimeout(() => {
    b.next(2);
    a.next(1);
}, 1000)

let a = new Subject();
let b = new Subject();
this.loaderData$ = merge(a.asObservable(), b.asObservable())
setTimeout(() => {
    b.next(2);
    setTimeout(() => { a.next(1) }, 1000)
}, 1000)

html:

<ts-loader [loaderData]="loaderData$ | async"></ts-loader>

@Component({
  selector: 'ts-loader',
  templateUrl: './ts-loader.component.html',
  styleUrls: ['./ts-loader.component.scss']
})
export class TsLoaderComponent {

  @Input()
  set loaderData(loaderData:any){
    console.log(loaderData)
}

The observable loaderData$ is passed to the child component through an async pipe. But the first piece of code inputs only 1 to be child component, whereas the second piece of code inputs both 1 and 2.

I am not able to figure out why are these observables working like this.

ps: I have a workaround to subscribe to the observable inside the child component and get the expected results. But I wanted to make it work with async pipes.

1
Both do the same thing. If not, please provide a minimal reproducible example of your issue. - user4676340
Yup thats behaving the same, as you are putting the observable output on same div. Its not visible. Instead put some delay on the inner setTimeout.. The difference can be noticed - siddiq rehman
This is your exact code. Again, if not, please provide a minimal reproducible example. I gave you the courtesy of making a sandbox (and trust me I don't do it often), now YOU must do it. I'm not a psychic, I can't just guess why it doesn't work on your side. - user4676340
Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers - user4676340

1 Answers

0
votes

It probably did happened already in your async pipe, async pipe only renders the latest result to screen so your 1 is overwriting 2. In order to test out place a tap

let a = new Subject();
let b = new Subject();
this.loaderData$ = merge(a.asObservable(), b.asObservable()).pipe(tap(console.log))

setTimeout(() => {
    b.next(2);
    a.next(1);
}, 1000)