Skip to content

Instantly share code, notes, and snippets.

@helzgate helzgate/rxjs2.html
Last active Jan 20, 2017

Embed
What would you like to do?
Scan, switchMap, MapTo, Merge, StartWitch
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://unpkg.com/@reactivex/rxjs@5.0.0-beta.7/dist/global/Rx.umd.js"></script>
<button style="margin-top:80px" id="start">Start</button>
<button style="margin-top:80px" id="stop">Stop</button>
<button style="margin-top:80px" id="reset">Reset</button>
</body>
</html>
const Observable = Rx.Observable;
const startButton = document.querySelector('#start');
const stopButton = document.querySelector('#stop');
const resetButton = document.querySelector('#reset');
const start$ = Observable.fromEvent(startButton, 'click');
const interval$ = Observable.interval(1000);
const stop$ = Observable.fromEvent(stopButton, 'click');
const reset$ = Observable.fromEvent(resetButton, 'click');
const data = {count:0};
const inc = (acc)=> ({count: acc.count + 1}); // you have to use the parenthesis around the object, otherwise it thinks it's a code block
const reset = (acc)=> data;
const intervalThatStops$ = interval$
.takeUntil(stop$); // stops the stream
const incOrReset$ = Observable.merge( // merge will allow || , so it will kick off on the first observable, or the second
intervalThatStops$.mapTo(inc), // mapTo returns a function and is later used in the scan operation down below
reset$.mapTo(reset) // mapTo returns a function and is later used in the scan operation down below
);
start$
.switchMapTo(incOrReset$) // SwitchMapTo saves you from using an arrow function if you don't care about consuming previous value.
.startWith(data) // initiates an initial value for the below functions so it doesn't have to wait for click event. This is why it shows count: 0 in the console before I even click start
.scan((acc, curr)=> curr(acc)) // scan allows you to store a value between each use, like a variable even after stopping stream, so when another stream is started it picks up where it left off.
.subscribe((x)=> console.log(x));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.