Wrap ES 2018 Asynchronous Iterators
See original GitHub issueI’d like to consume ES 2018 asynchronous iterators(see also the 2alities intro on the topic) as Bacon.EventStreams by wrapping the iteration by Bacon.fromBinder. This general interface would Bacon.js allow to work with new data sources. E.g. Node.js Readable Streams are Async Iterators now (Although here one could use Bacon.fromEvent('data') too.)
However, I cannot decide how to reflect the loss of subscribers in the Bacon.EventStream in the iteration of the AsyncIterable.
1.) Should the re-attachment of EventStream subscribers commence iteration at the point where the last previous subscriber was detached? I.e. should the iteration be paused? Or, 2.) should the iterator be returned, i.e. allowed to clean up, and the stream ended, when the subscriber count reaches 0?
Quick example:
var ten = countDown(10); // countDown is an async generator function
var tenStream = pausableFromAsyncIterator(ten); // implemented using Bacon.fromBinder
tenStream.take(2).log()
// --> 9, 8, <end>
tenStream.take(2).doEnd(() => ten.return()).log()
// --> 7, 6, <end>
// Or
var tenStream = fromAsyncIterator(countDown(10)); // implemented using Bacon.fromBinder
tenStream.take(2).log()
// --> 9, 8, <end>
tenStream.take(2).log()
// --> <end>
What is the Bacon.js way to do it?
Let me formulate the question differently:
Iterators are stateful (i.e. they keep the current “postition” of the iteration). Should we expose this statefulness in making the Bacon.EventStream stateful as well?
I know that for instance Bacon.fromArray and Bacon.sequentially commence publishing array items form the position where the loop position has been when the last subscriber was detached. Also reading a file every time from the beginning might not what one wants. BUT 1.) would mean that we need to share the AsyncIterator with other code parts (e.g. .doEnd(() => asyncIterator.return()) in order manage its lifetime or leaking memory. This would add complexity which I don’t like.
On the other hand 2.) might not be what the programmer familiar with Iterators would expect, BUT: Is unsubscribing and later re-subscribing to the same Bacon.EventStream really a programming pattern Bacon.js should support?
Issue Analytics
- State:
- Created 4 years ago
- Comments:6 (6 by maintainers)

Top Related StackOverflow Question
For now I use a rather naive recursive (see implementation below) adapter which lets me digest asynchronous iterables with Bacon.js like this:
Implemented so
@raimohanska No need to apologise! I just needed some feedback that my idea is not crazy or if I had missed something important.
👍 That’s excellent nevertheless!
Bacon.js is a well working reactive library without great omissions. Thanks to
.fromBinder,.withStateMachineand.transformusers can extend the functionality. Bug fixes is basically all what’s needed to keep my daily work going 😄