angular - angular2 observable scan once then subscribe by many async -


i need bind shared observable 2 times in different moments. second binding gets null when evaluated first time until next item appears.

here component class:

export class app {   subject = new behaviorsubject(1);   scan = this.subject.scan((current, change) => current + change, 0).share();   other = this.scan.map(item => item); } 

and here template:

<div>   <button (click)="clickedscan=true">show scan</button>   <button (click)="clickedother=true">show other</button>   <button (click)="subject.next(1)">next</button>   <div *ngif="clickedother">     other | async: <b>{{ '' + (other | async) }}</b>   </div>   <div *ngif="clickedscan">     scan | async: <b>{{ '' + (scan | async) }}</b>   </div> </div> 

and here plunker (update: plunker updated accepted answer)

share() needed since otherwise scan method being called repeatedly each subscriber next async binding done after time has no access last element. without using share() bindings work beginning scan called twice each subject.next() call (on separate item instances in plunker example). avoid duplicated scan calls many reasons - @ least not repeat same job same result each subscriber.

i wonder correct way avoid multiple share (i.e. using other observable method) calls , still provide last element whenever new async bound.

right, need hot observable share subsription rather having separate subscriptions. might interested in video andre: https://egghead.io/lessons/rxjs-demystifying-cold-and-hot-observables-in-rxjs. might interested in paul taylor's talk reactive 2015: https://youtu.be/qhjalubbqpg?t=385

basically, can rewrite code so:

import {subject, replaysubject} "rxjs/rx"; // need these 2  /* other code */  export class app {    // plain old subject clicks   // believe can event stream somewhere?   // sorry, don't know angular2   subject = new subject();    // replays last event observers on subscription   main = new replaysubject(1);    // apply transforms here if want   scan = this.main   other = this.main    constructor() {     // take events come in     this.subject        // start our observable initial event       .startwith(0)        // when subject emits, run , update       .scan((current, change) => current + change)        // can subscribe our replay subject       .subscribe(this.main);   } } 

hope helps.


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -