Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@MikeBild
Last active October 29, 2016 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikeBild/21351893e49729b59bb654f30b6274c7 to your computer and use it in GitHub Desktop.
Save MikeBild/21351893e49729b59bb654f30b6274c7 to your computer and use it in GitHub Desktop.
Resource lifetime binding to RxJS stream
const Rx = require('rx');
const coinsStream = Rx.Observable.fromArray([1,2,5,10,20,50,100].reverse());
Rx.Observable
// bind CoinResource lifetime to the stream lifetime
.using(() => new CoinResource(9), resource => coinsStream.map(x => ({ amount: resource.getValue(), coin: x })))
// calculations
.reduce((state, e) => {
const amount = (state.length > 0) ? state[state.length-1].rest : e.amount;
state.push({
coin: e.coin,
number: Math.floor(amount/e.coin),
rest: amount%e.coin,
});
return state;
}, [])
// debug
.do(x => console.log(JSON.stringify(x)))
.subscribe();
function CoinResource(value) {
this.value = value;
this.disposed = false;
this.getValue = () => {
if (this.disposed) throw new Error('Object is disposed');
return this.value;
};
this.dispose = () => {
// release resource
if (!this.disposed) {
this.disposed = true;
this.value = null;
}
};
}
@CarstenKoenig
Copy link

CarstenKoenig commented Oct 29, 2016

Nice one - although I would probably move out the rest from all the accumulated results and lift it into a (rest, picks) tuple

This way you don't have to index the array and don't need to ? .. : ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment