Imperatively push events into a Stream.
Note: @most/create is compatible most 1.x. It is not compatible with @most/core. In @most/core, simply implement the Stream interface, or use @most/adapter.
npm install --save most @most/create
Using add and end to push events and then end the stream.
import{create}from'@most/create'// Add events and then endconststream=create((add,end,error)=>{setTimeout(add,1000,'event 1')setTimeout(add,3000,'event 2')setTimeout(()=>{add('event 3')end()},10000)// OPTIONAL: Return a dispose function to clean up// resources when the stream endsreturn()=>console.log('dispose')})// Logs// 'event 1' after 1 second// 'event 2' after 3 seconds// 'event 3' after 10 seconds// 'dispose' after 10 secondsstream.forEach(x=>console.log(x));Using error to fail the stream and propagate an Error:
import{create}from'@most/create'// Add events and then failconststream=create((add,end,error)=>{setTimeout(add,1000,'event 1');setTimeout(()=>error(newError('oops!')),3000)});// Logs// 'event 1' after 1 second// '[Error: oops!]' after 3 secondsstream.forEach(x=>console.log(x)).catch(e=>console.error(e));// Catch the error as a promisePublisher :: (Error e) ⇒ ((a → void) → (b → void) → (e → void)) → (void → void)
Create a push-stream for imperatively pushing events, primarily for situations where declarative sources can't be used.
The publisher function receives 3 functions as arguments, which it can use to publish events, end the stream, or signal an error. It may return a dispose function. The dispose function will be called once all consumers have lost interest in the stream, and should free any resources held by the publisher.
Note that the publisher will not be called until there is demand for the stream's events. Specifically, the publisher will be called when the number of observers goes from zero to one. Likewise, the dispose function will be called when the number of observers again returns to zero. The publisher would then be called again if the number of observers subsequently goes from zero to one, and so on.
The publisher function can use add, end, and error:
add(x)- Addxto the streamend()- End the stream. Any later calls toadd,end, orerrorwill be no-ops.error(e)- Signal that the stream has failed and cannot produce more events.
Important
If you never call
endorerror, the stream will never end, and consumers will wait forever for additional events.Pulling the
add,end, and/orerrorfunctions out of the publisher closure is not supported.
// Unsupported:letemitEvent,emitEnd,emitErrorconststream=most.create((add,end,error)=>{emitEvent=addemitEnd=endemitError=error})emitEvent(123)emitEnd()If the publisher returns a dispose function, it will be called when the stream ends or errors--for example, when the publisher explicitly calls end or error, or when all consumers lose interest.
dispose- free resources held by the publisher
Note that if the stream neither ends nor fails, the dispose function will never be called.