Skip to content

Instantly share code, notes, and snippets.

@whisher
Last active January 8, 2017 00:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whisher/012092b9d17a95e895b3e6b3d937438e to your computer and use it in GitHub Desktop.
Save whisher/012092b9d17a95e895b3e6b3d937438e to your computer and use it in GitHub Desktop.
class AppComponent {
@ViewChild('btnPlus') btnPlus;
@ViewChild('btnMinus') btnMinus;
ngOnInit() {
const start = 0;
var plus$ = Observable.fromEvent(this.getNativeElement(this.btnPlus), 'click');
var minus$ = Observable.fromEvent(this.getNativeElement(this.btnMinus), 'click');
var plusOrMinus$ = Observable.merge(plus$.mapTo(1), minus$.mapTo(-1));
plusOrMinus$
.scan((acc,curr) => acc+curr, start)
.subscribe(x => console.log(x));
}
getNativeElement(element){
return element.nativeElement;
}
}
UPDATE
const start = 0;
const min = 0;
const max = 3
const plus$ = Observable.fromEvent(this.getNativeElement(this.btnPlus), 'click');
const minus$ = Observable.fromEvent(this.getNativeElement(this.btnMinus), 'click');
const plusOrMinus$ = Observable.merge(plus$.mapTo(1), minus$.mapTo(-1));
plusOrMinus$
.scan((acc,curr) =>{
if(acc === start){
if(curr > 0){
return acc+curr;
}
}
if(acc > start){
return acc+curr;
}
else{
throw new Error('0 value');
}
},
start)
.catch((e,obs)=> obs.startWith(0))
.subscribe(x => console.log(x));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment