-
-
Save xgrommx/bf30bcc31884a32b6c6e to your computer and use it in GitHub Desktop.
Bacon.waitUntil
This file contains hidden or 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
/** | |
* Waits until the supplied stream emits a value, and then | |
* continues by emitting the last value emitted on the target. | |
* Useful when you want to gate on an event emitter. | |
*/ | |
Bacon.Observable.prototype.waitUntil = function(item) { | |
// Cache the last value to come out of the source. | |
let last; | |
const unsub = this.onValue(x => last = x); | |
return Bacon.fromBinder(sink => { | |
// And sink it once the target emits a value. | |
// Note that the target's emitted value is ignored. | |
const outerUnsub = item.onValue(_ => sink(last)); | |
return () => { | |
unsub(); | |
outerUnsub(); | |
}; | |
}); | |
}; | |
// Example: Same functionality as Bacon's Property.sample, gets the latest emitted value of the first stream every 300ms. | |
Bacon.repeatedly(100, [1,2,3,4,5,6]) | |
.waitUntil(Bacon.interval(300)) | |
.onValue(console.log.bind(console)) | |
// Example: Wait for clicks and emit whatever the last value the first stream has emitted. | |
Bacon.repeatedly(100, [1,2,3,4,5,6]) | |
.waitUntil($(document).asEventStream('click')) | |
.onValue(console.log.bind(console)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment