mostjs - creating streams from custom sources

564 Views Asked by At

I am curious about current best practices for creating streams from sources that may not conform to an existing stream creation method (https://github.com/cujojs/most/blob/master/docs/api.md)

Example using Firebase's ref.on('child_added', function(snap){}):

most.fromEvent('child_added', ref) //ERROR

I can't use .fromEvent... although ref implements some sort of on, it does not seem to conform to the EventEmitter interface (addEventListener, removeEventListener)


ref.on('child_added', function(snap){ emitter.emit('value', snap) })

most.fromEvent('value', emitter)

Manually emitting events, is the best I can think of at the moment...


// https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/create.md

Rx.Observable.create(function(observer){
  ref.on('child_added', function(snap){ observer.next(snap) })
})

Is there a similar mechanism to custom create a stream, a la Rx?

Are there better ways I am missing?

2

There are 2 best solutions below

0
On

Check on how to use @most/create

https://github.com/mostjs/create

It allows to manually emit events - similar to how you would do it with rxJS

0
On

Another option might be to shim the interface that your firebase library exposes to fit most's fromEvent constructor.

Looking at the source code for fromEvent, we can see that it supports two interfaces for event sources:

With that knowledge, we can implement a shim function to create a stream from the { on, off } interface:

function fromEvent (eventName, source) {
  if (typeof source.on === 'function' && typeof source.off === 'function') {
    return most.fromEvent(eventName, {
      addListener: source.on,
      removeListener: source.off
    });
  } else {
    return most.fromEvent.apply(null, arguments)
  }
}

This can be nicer than using create, as the EventEmitterSource performs scheduling of the event on the next tick of the event loop, and handles disposing of the event listener when the stream ends.