Last active
October 29, 2016 09:13
-
-
Save MikeBild/21351893e49729b59bb654f30b6274c7 to your computer and use it in GitHub Desktop.
Resource lifetime binding to RxJS stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice one - although I would probably move out the
rest
from all the accumulated results and lift it into a(rest, picks)
tupleThis way you don't have to index the array and don't need to
? .. : ...