baconjs
- Version 3.0.19
- Published
- 722 kB
- No dependencies
- MIT license
Install
npm i baconjs
yarn add baconjs
pnpm add baconjs
Overview
A small functional reactive programming lib for JavaScript.
Index
Variables
Functions
- combineAsArray()
- combineTemplate()
- combineTwo()
- combineWith()
- concatAll()
- constant()
- fromArray()
- fromBinder()
- fromCallback()
- fromESObservable()
- fromEvent()
- fromEventTarget()
- fromNodeCallback()
- fromPoll()
- fromPromise()
- getScheduler()
- groupSimultaneous()
- hasValue()
- interval()
- isEnd()
- isError()
- isEvent()
- isInitial()
- isNext()
- isProperty()
- later()
- mergeAll()
- never()
- once()
- onValues()
- repeat()
- repeatedly()
- retry()
- sequentially()
- setScheduler()
- silence()
- spy()
- try()
- update()
- when()
- zipAsArray()
- zipWith()
Classes
EventStream
- bufferWithCount()
- bufferWithTime()
- bufferWithTimeOrCount()
- changes()
- concat()
- flatMap()
- flatMapConcat()
- flatMapError()
- flatMapEvent()
- flatMapFirst()
- flatMapLatest()
- flatMapWithConcurrencyLimit()
- flatScan()
- groupBy()
- map()
- merge()
- not()
- startWith()
- subscribeInternal()
- toEventStream()
- toProperty()
- transform()
- transformChanges()
- withLatestFrom()
- withStateMachine()
Observable
- awaiting()
- bufferingThrottle()
- changes()
- combine()
- concat()
- debounce()
- debounceImmediate()
- decode()
- delay()
- deps()
- desc
- diff()
- doAction()
- doEnd()
- doError()
- doLog()
- endAsValue()
- endOnError()
- errors()
- filter()
- first()
- firstToPromise()
- flatMap()
- flatMapConcat()
- flatMapError()
- flatMapEvent()
- flatMapFirst()
- flatMapLatest()
- flatMapWithConcurrencyLimit()
- fold()
- forEach()
- groupBy()
- holdWhen()
- id
- initialDesc
- inspect()
- internalDeps()
- last()
- log()
- map()
- mapEnd()
- mapError()
- name()
- not()
- onEnd()
- onError()
- onValue()
- onValues()
- reduce()
- sampledBy()
- scan()
- skip()
- skipDuplicates()
- skipErrors()
- skipUntil()
- skipWhile()
- slidingWindow()
- startWith()
- subscribe()
- subscribeInternal()
- take()
- takeUntil()
- takeWhile()
- throttle()
- toEventStream()
- toPromise()
- toProperty()
- toString()
- transform()
- transformChanges()
- withDesc()
- withDescription()
- withLatestFrom()
- withStateMachine()
- zip()
Interfaces
Type Aliases
- Binder
- EventLike
- EventSink
- EventStreamDelay
- EventTransformer
- FlexibleSink
- Function0
- Function1
- Function2
- Function3
- Function4
- Function5
- Function6
- Pattern
- Pattern1
- Pattern2
- Pattern3
- Pattern4
- Pattern5
- Pattern6
- Reply
- Sink
- Spy
- Subscribe
- Unsub
- UpdatePattern
- UpdatePattern1
- UpdatePattern2
- UpdatePattern3
- UpdatePattern4
- UpdatePattern5
- UpdatePattern6
- VoidSink
Variables
variable $
const $: { asEventStream( eventName: string, selector: string | undefined, eventTransformer: any ): EventStream<any>; init(jQuery: any): void;};
JQuery/Zepto integration support
variable combine
const combine: { <R>(fn: Function0<R>): Property<R>; <V, R>(a: Observable<V>, fn: Function1<V, R>): Property<R>; <V, V2, R>( a: Observable<V>, b: Observable<V2>, fn: Function2<V, V2, R> ): Property<R>; <V, V2, V3, R>( a: Observable<V>, b: Observable<V2>, c: Observable<V3>, fn: Function3<V, V2, V3, R> ): Property<R>; <V, V2, V3, V4, R>( a: Observable<V>, b: Observable<V2>, c: Observable<V3>, d: Observable<V4>, fn: Function4<V, V2, V3, V4, R> ): Property<R>; <V, V2, V3, V4, V5, R>( a: Observable<V>, b: Observable<V2>, c: Observable<V3>, d: Observable<V4>, e: Observable<V5>, fn: Function5<V, V2, V3, V4, V5, R> ): Property<R>; <V, V2, V3, V4, V5, V6, R>( a: Observable<V>, b: Observable<V2>, c: Observable<V3>, d: Observable<V4>, e: Observable<V5>, f: Observable<V6>, fn: Function6<V, V2, V3, V4, V5, V6, R> ): Property<R>; <R>(observables: Observable<any>[], fn: Function): Property<R>; <V, R>(fn: Function1<V, R>, a: Observable<V>): Property<R>; <V, V2, R>( fn: Function2<V, V2, R>, a: Observable<V>, b: Observable<V2> ): Property<R>; <V, V2, V3, R>( fn: Function3<V, V2, V3, R>, a: Observable<V>, b: Observable<V2>, c: Observable<V3> ): Property<R>; <V, V2, V3, V4, R>( fn: Function4<V, V2, V3, V4, R>, a: Observable<V>, b: Observable<V2>, c: Observable<V3>, d: Observable<V4> ): Property<R>; <V, V2, V3, V4, V5, R>( fn: Function5<V, V2, V3, V4, V5, R>, a: Observable<V>, b: Observable<V2>, c: Observable<V3>, d: Observable<V4>, e: Observable<V5> ): Property<R>; <V, V2, V3, V4, V5, V6, R>( fn: Function6<V, V2, V3, V4, V5, V6, R>, a: Observable<V>, b: Observable<V2>, c: Observable<V3>, d: Observable<V4>, e: Observable<V5>, f: Observable<V6> ): Property<R>; <R>(fn: Function, observables: Observable<any>[]): Property<R>;};
variable more
const more: any;
Reply for "more data, please".
variable noMore
const noMore: any;
Reply for "no more data, please".
variable nullSink
const nullSink: Sink<any>;
variable nullVoidSink
const nullVoidSink: VoidSink;
variable version
const version: string;
Bacon.js version as string
Functions
function combineAsArray
combineAsArray: <V>( ...streams: (Observable<V> | Observable<V>[])[]) => Property<V[]>;
Combines Properties, EventStreams and constant values so that the result Property will have an array of the latest values from all sources as its value. The inputs may contain both Properties and EventStreams.
```js property = Bacon.constant(1) stream = Bacon.once(2) constant = 3 Bacon.combineAsArray(property, stream, constant) # produces the value [1,2,3] ```
Parameter streams
streams and properties to combine
function combineTemplate
combineTemplate: <T>(template: T) => Property<CombinedTemplate<T>>;
function combineTwo
combineTwo: <V, V2, R>( left: Observable<V>, right: Observable<V2>, f: Function2<V, V2, R>) => Property<R>;
function combineWith
combineWith: { <R>(fn: Function0<R>): Property<R>; <V, R>(a: Observable<V>, fn: Function1<V, R>): Property<R>; <V, V2, R>( a: Observable<V>, b: Observable<V2>, fn: Function2<V, V2, R> ): Property<R>; <V, V2, V3, R>( a: Observable<V>, b: Observable<V2>, c: Observable<V3>, fn: Function3<V, V2, V3, R> ): Property<R>; <V, V2, V3, V4, R>( a: Observable<V>, b: Observable<V2>, c: Observable<V3>, d: Observable<V4>, fn: Function4<V, V2, V3, V4, R> ): Property<R>; <V, V2, V3, V4, V5, R>( a: Observable<V>, b: Observable<V2>, c: Observable<V3>, d: Observable<V4>, e: Observable<V5>, fn: Function5<V, V2, V3, V4, V5, R> ): Property<R>; <V, V2, V3, V4, V5, V6, R>( a: Observable<V>, b: Observable<V2>, c: Observable<V3>, d: Observable<V4>, e: Observable<V5>, f: Observable<V6>, fn: Function6<V, V2, V3, V4, V5, V6, R> ): Property<R>; <R>(observables: Observable<any>[], fn: Function): Property<R>; <V, R>(fn: Function1<V, R>, a: Observable<V>): Property<R>; <V, V2, R>( fn: Function2<V, V2, R>, a: Observable<V>, b: Observable<V2> ): Property<R>; <V, V2, V3, R>( fn: Function3<V, V2, V3, R>, a: Observable<V>, b: Observable<V2>, c: Observable<V3> ): Property<R>; <V, V2, V3, V4, R>( fn: Function4<V, V2, V3, V4, R>, a: Observable<V>, b: Observable<V2>, c: Observable<V3>, d: Observable<V4> ): Property<R>; <V, V2, V3, V4, V5, R>( fn: Function5<V, V2, V3, V4, V5, R>, a: Observable<V>, b: Observable<V2>, c: Observable<V3>, d: Observable<V4>, e: Observable<V5> ): Property<R>; <V, V2, V3, V4, V5, V6, R>( fn: Function6<V, V2, V3, V4, V5, V6, R>, a: Observable<V>, b: Observable<V2>, c: Observable<V3>, d: Observable<V4>, e: Observable<V5>, f: Observable<V6> ): Property<R>; <R>(fn: Function, observables: Observable<any>[]): Property<R>;};
Combines given *n* Properties and EventStreams using the given n-ary function
f(v1, v2 ...)
.To calculate the current sum of three numeric Properties, you can do
function sum3(x,y,z) { return x + y + z }Bacon.combineWith(sum3, p1, p2, p3)
function concatAll
concatAll: <V>( ...streams_: (Observable<V> | Observable<V>[])[]) => EventStream<V>;
Concatenates given array of EventStreams or Properties. Works by subscribing to the first source, and listeing to that until it ends. Then repeatedly subscribes to the next source, until all sources have ended.
See [
concat
](#observable-concat)
function constant
constant: <V>(x: V) => Property<V>;
Creates a constant property with value
x
.
function fromArray
fromArray: <T>(values: (T | Event<T>)[]) => EventStream<T>;
Creates an EventStream that delivers the given series of values (given as array) to the first subscriber. The stream ends after these values have been delivered. You can also send [
Bacon.Error
](classes/error.html) events, or any combination of pure values and error events like this: `Bacon.fromArray([1, new Bacon.Error()])Parameter values
Array of values or events to repeat
function fromBinder
fromBinder: <V>( binder: Binder<V>, eventTransformer?: EventTransformer<V>) => EventStream<V>;
If none of the other factory methods above apply, you may of course roll your own EventStream by using
fromBinder
.[
Bacon.fromBinder(subscribe)
](#bacon-frombinder "Bacon.fromBinder(subscribe)") The parametersubscribe
is a function that accepts asink
which is a function that yoursubscribe
function can "push" events to.For example:
```js var stream = Bacon.fromBinder(function(sink) { sink("first value") sink([new Bacon.Next("2nd"), new Bacon.Next("3rd")]) sink(new Bacon.Error("oops, an error")) sink(new Bacon.End()) return function() { // unsub functionality here, this one's a no-op } }) stream.log() ```
As shown in the example, you can push
- A plain value, like
"first value"
- An [Event
](#event) object including [Bacon.Error
](#bacon-error) (wraps an error) and [Bacon.End
](#bacon-end) (indicates stream end). - An array of [event](#event) objects at onceOther examples can be found on [JSFiddle](http://jsfiddle.net/PG4c4/) and the [Bacon.js blog](http://baconjs.blogspot.fi/2013/12/wrapping-things-in-bacon.html).
The
subscribe
function must return a function. Let's call that functionunsubscribe
. The returned function can be used by the subscriber (directly or indirectly) to unsubscribe from the EventStream. It should release all resources that the subscribe function reserved.The
sink
function may return [Bacon.noMore
](#bacon-nomore) (as well as [Bacon.more
](#bacon-more) or any other value). If it returns [Bacon.noMore
](#bacon-nomore), no further events will be consumed by the subscriber. Thesubscribe
function may choose to clean up all resources at this point (e.g., by callingunsubscribe
). This is usually not necessary, because further calls tosink
are ignored, but doing so can increase performance in [rare cases](https://github.com/baconjs/bacon.js/issues/484).The EventStream will wrap your
subscribe
function so that it will only be called when the first stream listener is added, and theunsubscribe
function is called only after the last listener has been removed. The subscribe-unsubscribe cycle may of course be repeated indefinitely, so prepare for multiple calls to the subscribe function.Parameter binder
Parameter eventTransformer
function fromCallback
fromCallback: <V>(f: Function, ...args: any[]) => EventStream<V>;
Creates an EventStream from a function that accepts a callback. The function is supposed to call its callback just once. For example:
```js Bacon.fromCallback(callback => callback("bacon")) ```
This would create a stream that outputs a single value "Bacon!" and ends after that. The use of setTimeout causes the value to be delayed by 1 second.
You can also give any number of arguments to [
fromCallback
](#bacon-fromcallback), which will be passed to the function. These arguments can be simple variables, Bacon EventStreams or Properties. For example the following will output "Bacon rules":```js bacon = Bacon.constant('bacon') Bacon.fromCallback(function(a, b, callback) { callback(a + ' ' + b); }, bacon, 'rules').log(); ```
Parameter f
Parameter args
Returns
{EventStream}
function fromESObservable
fromESObservable: <V>(_observable: any) => EventStream<V>;
Creates an EventStream from an [ES Observable](https://github.com/tc39/proposal-observable). Input can be any ES Observable implementation including RxJS and Kefir.
function fromEvent
fromEvent: <V>( target: any, eventSource: string | EventSourceFn, eventTransformer?: EventTransformer<V>) => EventStream<V>;
creates an EventStream from events on a DOM EventTarget or Node.JS EventEmitter object, or an object that supports event listeners using
on
/off
methods. You can also pass an optional function that transforms the emitted events' parameters.The simple form:
```js Bacon.fromEvent(document.body, "click").onValue(function() { alert("Bacon!") }) ```
Using a binder function:
```js Bacon.fromEvent( window, function(binder, listener) { binder("scroll", listener, {passive: true}) } ).onValue(function() { console.log(window.scrollY) }) ```
Parameter target
Parameter eventSource
Parameter eventTransformer
function fromEventTarget
fromEventTarget: <V>( target: any, eventSource: string | EventSourceFn, eventTransformer?: EventTransformer<V>) => EventStream<V>;
creates an EventStream from events on a DOM EventTarget or Node.JS EventEmitter object, or an object that supports event listeners using
on
/off
methods. You can also pass an optional function that transforms the emitted events' parameters.The simple form:
```js Bacon.fromEvent(document.body, "click").onValue(function() { alert("Bacon!") }) ```
Using a binder function:
```js Bacon.fromEvent( window, function(binder, listener) { binder("scroll", listener, {passive: true}) } ).onValue(function() { console.log(window.scrollY) }) ```
Parameter target
Parameter eventSource
Parameter eventTransformer
function fromNodeCallback
fromNodeCallback: <V>(f: Function, ...args: any[]) => EventStream<V>;
Behaves the same way as
Bacon.fromCallback
, except that it expects the callback to be called in the Node.js convention:callback(error, data)
, where error is null if everything is fine. For example:var Bacon = require('baconjs').Bacon,fs = require('fs');var read = Bacon.fromNodeCallback(fs.readFile, 'input.txt');read.onError(function(error) { console.log("Reading failed: " + error); });read.onValue(function(value) { console.log("Read contents: " + value); });
function fromPoll
fromPoll: <V>(delay: number, poll: PollFunction<V>) => EventStream<V>;
Polls given function with given interval. Function should return Events: either [
Bacon.Next
](classes/next.html) or [Bacon.End
](classes/end.html). Polling occurs only when there are subscribers to the stream. Polling ends permanently whenf
returns [Bacon.End
](classes/end.html).Parameter delay
poll interval in milliseconds
Parameter poll
function to be polled
function fromPromise
fromPromise: <V>( promise: Promise<V>, abort?: boolean, eventTransformer?: EventTransformer<V>) => EventStream<V>;
Creates an EventStream from a Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the optional abort flag (i.e. ´fromPromise(p, true)´ to have the
abort
method of the given promise be called when all subscribers have been removed from the created stream. You can also pass an optional function that transforms the promise value into Events. The default is to transform the value into[new Bacon.Next(value), new Bacon.End()]
. Check out this [example](https://github.com/raimohanska/baconjs-examples/blob/master/resources/public/index.html).Parameter source
promise object
Parameter abort
should we call the
abort
method of the Promise on unsubscribe. This is a nonstandard feature you should probably ignore.Parameter eventTransformer
Returns
{EventStream}
function getScheduler
getScheduler: () => Scheduler;
function groupSimultaneous
groupSimultaneous: <V>( ...streams: (Observable<V> | Observable<V>[])[]) => EventStream<V[][]>;
function hasValue
hasValue: <V>(e: Event<V>) => e is Value<V>;
Returns true if the given event is a [Value](classes/value.html), i.e. a [Next](classes/next.html) or an [Initial](classes/error.html) value of an [Observable](classes/observable.html).
function interval
interval: <V>(delay: number, value: V) => EventStream<V>;
Repeats the single element indefinitely with the given interval (in milliseconds)
Parameter delay
Repeat delay in milliseconds
Parameter value
The single value to repeat
function isEnd
isEnd: <V>(e: Event<V>) => e is End;
Returns true if the given event is an [End](classes/end.html)
function isError
isError: <V>(e: Event<V>) => e is Error;
Returns true if the given event is an [Error](classes/error.html) event of an [Observable](classes/observable.html).
function isEvent
isEvent: <V>(e: any) => e is Event<V>;
Returns true if the given object is an [Event](classes/event.html).
function isInitial
isInitial: <V>(e: Event<V>) => e is Initial<V>;
Returns true if the given event is an [Initial](classes/initial.html) value of a [Property](classes/property.html).
function isNext
isNext: <V>(e: Event<V>) => e is Next<V>;
Returns true if the given event is a [Next](classes/next.html)
function isProperty
isProperty: <V>(x: any) => x is Property<V>;
function later
later: <V>(delay: number, value: V) => EventStream<V>;
Creates a single-element stream that emits given value after given delay and ends.
Parameter delay
delay in milliseconds
Parameter value
value to be emitted
function mergeAll
mergeAll: <V>(...streams: (Observable<V> | Observable<V>[])[]) => EventStream<V>;
Merges given array of EventStreams or Properties, by collecting the values from all of the sources into a single EventStream.
See also [
merge
](classes/eventstream.html#merge).
function never
never: <V>() => EventStream<V>;
Creates an EventStream that immediately ends.
function once
once: <V>(value: V | Event<V>) => EventStream<V>;
Creates an EventStream that delivers the given single value for the first subscriber. The stream will end immediately after this value. You can also send an [
Bacon.Error
](#bacon-error) event instead of a value:Bacon.once(new Bacon.Error("fail"))
.Parameter value
the value or event to emit
function onValues
onValues: (...args: any[]) => Unsub;
A shorthand for combining multiple sources (streams, properties, constants) as array and assigning the side-effect function f for the values. The following example would log the number 3.
```js function f(a, b) { console.log(a + b) } Bacon.onValues(Bacon.constant(1), Bacon.constant(2), f) ```
function repeat
repeat: <V>( generator: (iteration: number) => Observable<V> | undefined) => EventStream<V>;
Calls generator function which is expected to return an observable. The returned EventStream contains values and errors from the spawned observable. When the spawned observable ends, the generator is called again to spawn a new observable.
This is repeated until the generator returns a falsy value (such as
undefined
orfalse
).The generator function is called with one argument — iteration number starting from
0
.Here's an example:
Bacon.repeat(function(i) {if (i < 3) {return Bacon.once(i);} else {return false;}}).log()The example will produce values 0, 1 and 2.
Parameter generator
Returns
{EventStream}
function repeatedly
repeatedly: <V>(delay: number, values: (V | Event<V>)[]) => EventStream<V>;
Repeats given elements indefinitely with given interval in milliseconds. For example,
repeatedly(10, [1,2,3])
would lead to1,2,3,1,2,3...
to be repeated indefinitely.Parameter delay
between values, in milliseconds
Parameter values
array of values to repeat
function retry
retry: <V>(options: RetryOptions<V>) => EventStream<V>;
Used to retry the call when there is an [
Error
](classes/error.html) event in the stream produced by thesource
function.```js var triggeringStream, ajaxCall // <- ajaxCall gives Errors on network or server errors ajaxResult = triggeringStream.flatMap(function(url) { return Bacon.retry({ source: function(attemptNumber) { return ajaxCall(url) }, retries: 5, isRetryable: function (error) { return error.httpStatusCode !== 404; }, delay: function(context) { return 100; } // Just use the same delay always }) }) ```
Parameter options
(click for details)
function sequentially
sequentially: <V>(delay: number, values: (V | Event<V>)[]) => EventStream<V>;
Creates a stream containing given values (given as array). Delivered with given interval in milliseconds.
Parameter delay
between elements, in milliseconds
Parameter array
of values or events
function setScheduler
setScheduler: (newScheduler: Scheduler) => void;
function silence
silence: <V>(duration: number) => EventStream<V>;
Creates a stream that ends after given amount of milliseconds, without emitting any values.
Parameter duration
duration of silence in milliseconds
function spy
spy: (spy: Spy) => number;
Adds your function as a "spy" that will get notified on all new Observables. This will allow a visualization/analytics tool to spy on all Bacon activity.
function try
try: <In, Out>(f: (value: In) => Out) => (value: In) => EventStream<Out>
Bacon.try
is a helper for creating an EventStream of a single value, or a single Error event in case the given function throws an exception.For example, you can use
Bacon.try
to handle JSON parse errors:```js var jsonStream = Bacon .once('{"this is invalid json"') .flatMap(Bacon.try(JSON.parse))
jsonStream.onError(function(err) { console.error("Failed to parse JSON", err) })
function update
update: <Out>(initial: Out, ...patterns: UpdatePattern<Out>[]) => Property<Out>;
Creates a Property from an initial value and updates the value based on multiple inputs. The inputs are defined similarly to [
Bacon.when
](#bacon-when), like this:```js var result = Bacon.update( initial, [x,y,z, (previous,x,y,z) => { ... }], [x,y, (previous,x,y) => { ... }]) ```
As input, each function above will get the previous value of the
result
Property, along with values from the listed Observables. The value returned by the function will be used as the next value ofresult
.Just like in [
Bacon.when
](#when), only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream.Here's a simple gaming example:
```js let scoreMultiplier = Bacon.constant(1) let hitUfo = Bacon.interval(1000) let hitMotherShip = Bacon.later(10000) let score = Bacon.update( 0, [hitUfo, scoreMultiplier, (score, _, multiplier) => score + 100 * multiplier ], [hitMotherShip, (score, _) => score + 2000 ] ) ```
In the example, the
score
property is updated when eitherhitUfo
orhitMotherShip
occur. ThescoreMultiplier
Property is sampled to take multiplier into account whenhitUfo
occurs.Parameter initial
Parameter patterns
Returns
{Property}
function when
when: <O>(...patterns: Pattern<O>[]) => EventStream<O>;
The
when
method provides a generalization of the [zip
](classes/observable.html#zip) function. While zip synchronizes events from multiple streams pairwse, the join patterns used inwhen
allow the implementation of more advanced synchronization patterns.Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick.
```js Bacon.when( [tick, keyEvent, function(_, k) { handleKeyEvent(k); return handleTick(); }], [tick, handleTick]) ```
Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick.
Join patterns are indeed a generalization of zip, and for EventStreams, zip is equivalent to a single-rule join pattern. The following observables have the same output, assuming that all sources are EventStreams.
```js Bacon.zipWith(a,b,c, combine) Bacon.when([a,b,c], combine) ```
Note that [
Bacon.when
](#bacon-when) does not trigger updates for events from Properties though; if you use a Property in your pattern, its value will be just sampled when all the other sources (EventStreams) have a value. This is useful when you need a value of a Property in your calculations. If you want your pattern to fire for a Property too, you can convert it into an EventStream using [property.changes()
](#property-changes) or [property.toEventStream()
](#property-toeventstream)Parameter patterns
Join patterns
function zipAsArray
zipAsArray: <V>(...args: (Observable<V> | Observable<V>[])[]) => Observable<V[]>;
Zips the array of EventStreams / Properties in to a new EventStream that will have an array of values from each source as its value. Zipping means that events from each source are combined pairwise so that the 1st event from each source is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source.
Be careful not to have too much "drift" between streams. If one stream produces many more values than some other excessive buffering will occur inside the zipped observable.
Example:
```js x = Bacon.fromArray([1,2,3]) y = Bacon.fromArray([10, 20, 30]) z = Bacon.fromArray([100, 200, 300]) Bacon.zipAsArray(x, y, z)
# produces values [1, 10, 100], [2, 20, 200] and [3, 30, 300] ```
function zipWith
zipWith: <Out>( f: (...any: any[]) => Out, ...streams: Observable<any>[]) => EventStream<Out>;
Like [
zipAsArray
](#bacon-zipasarray) but uses the given n-ary function to combine the n values from n sources, instead of returning them in an Array.
Classes
class Bus
class Bus<V> extends EventStream<V> {}
An [
EventStream
](eventstream.html) that allows you to [push
](#push) values into the stream.It also allows plugging other streams into the Bus, as inputs. The Bus practically merges all plugged-in streams and the values pushed using the [
push
](#push) method.
constructor
constructor();
property ended
ended: boolean;
property pushing
pushing: boolean;
property pushQueue
pushQueue?: V[];
property sink
sink?: EventSink<V>;
property subscriptions
subscriptions: Subscription<V>[];
method end
end: () => Reply;
Ends the stream. Sends an [End](end.html) event to all subscribers. After this call, there'll be no more events to the subscribers. Also, the [
push
](#push), [error
](#error) and [plug
](#plug) methods have no effect.
method error
error: (error: any) => Reply;
Pushes an error to this stream.
method guardedSink
guardedSink: (input: Observable<V>) => EventSink<V>;
method plug
plug: <V2 extends V>(input: Observable<V2>) => (() => void) | undefined;
Plugs the given stream as an input to the Bus. All events from the given stream will be delivered to the subscribers of the Bus. Returns a function that can be used to unplug the same stream.
The plug method practically allows you to merge in other streams after the creation of the Bus.
Returns
a function that can be called to "unplug" the source from Bus.
method push
push: (value: V) => Reply;
Pushes a new value to the stream.
method subscribeAll
subscribeAll: (newSink: EventSink<V>) => () => void;
method subscribeInput
subscribeInput: (subscription: Subscription<V>) => Unsub;
method unsubAll
unsubAll: () => void;
method unsubscribeInput
unsubscribeInput: (input: Observable<any>) => void;
class CompositeUnsubscribe
class CompositeUnsubscribe {}
constructor
constructor(ss?: Subscription[]);
property starting
starting: Subscription[];
property subscriptions
subscriptions: Unsub[];
property unsubscribed
unsubscribed: boolean;
method add
add: (subscription: Subscription) => void;
method count
count: () => number;
method empty
empty: () => boolean;
method remove
remove: (unsub: Unsub) => void;
method unsubscribe
unsubscribe: () => void;
class Desc
class Desc {}
constructor
constructor(context: any, method: string, args?: any[]);
property args
args: any[];
property cachedDeps
cachedDeps?: Observable<any>[];
property context
context: any;
property method
method?: string;
method deps
deps: () => Observable<any>[];
method toString
toString: () => string;
class End
class End extends NoValue {}
An event that indicates the end of an [EventStream](classes/eventstream.html) or a [Property](classes/property.html). No more events can be emitted after this one.
Can be distinguished from other events using [isEnd](../globals.html#isend)
class Error
class Error extends NoValue {}
An event carrying an error. You can use [onError](observable.html#onerror) to subscribe to errors.
constructor
constructor(error: any);
property error
error: any;
The actual error object carried by this event
property isError
isError: boolean;
method toString
toString: () => string;
class Event
abstract class Event<V> {}
Base class for all events passed through [EventStreams](eventstream.html) and [Properties](property.html).
property hasValue
hasValue: boolean;
property id
id: number;
property isEnd
isEnd: boolean;
property isError
isError: boolean;
property isEvent
isEvent: boolean;
property isInitial
isInitial: boolean;
property isNext
isNext: boolean;
method filter
filter: (f: (value: V) => boolean) => boolean;
method fmap
abstract fmap: <V2>(f: (value: V) => V2) => Event<V2>;
method inspect
inspect: () => string;
method log
log: () => any;
method toNext
toNext: () => Event<V>;
class EventStream
class EventStream<V> extends Observable<V> {}
EventStream represents a stream of events. It is an Observable object, meaning that you can listen to events in the stream using, for instance, the [
onValue
](#onvalue) method with a callback.To create an EventStream, you'll want to use one of the following factory methods:
- From DOM EventTarget or Node.JS EventEmitter objects using [fromEvent](../globals.html#fromevent) - From a Promise using [fromPromise](../globals.html#frompromise) - From an unary callback using [fromCallback](../globals.html#fromcallback) - From a Node.js style callback using [fromNodeCallback](../globals.html#fromnodecallback) - From RxJs or Kefir observables using [fromESObservable](../globals.html#fromesobservable) - By polling a synchronous function using [fromPoll](../globals.html#fromPoll) - Emit a single event instantly using [once](../globals.html#once) - Emit a single event with a delay [later](../globals.html#later) - Emit the same event indefinitely using [interval](../globals.html#interval) - Emit an array of events instantly [fromArray](../globals.html#fromarray) - Emit an array of events with a delay [sequentially](../globals.html#sequentially) - Emit an array of events repeatedly with a delay [repeatedly](../globals.html#repeatedly) - Use a generator function to be called repeatedly [repeat](../globals.html#repeat) - Create a stream that never emits an event, ending immediately [never](../globals.html#never) - Create a stream that never emits an event, ending with a delay [silence](../globals.html#silence) - Create stream using a custom binder function [fromBinder](../globals.html#frombinder) - Wrap jQuery events using [asEventStream](../globals.html#_)
constructor
constructor( desc: Desc, subscribe: Subscribe<V>, handler?: EventSink<V>, options?: EventStreamOptions);
method bufferWithCount
bufferWithCount: (count: number) => EventStream<V[]>;
Buffers stream events with given count. The buffer is flushed when it contains the given number of elements or the source stream ends.
So, if you buffer a stream of
[1, 2, 3, 4, 5]
with count2
, you'll get output events with values[1, 2]
,[3, 4]
and[5]
.Parameter count
method bufferWithTime
bufferWithTime: (delay: number | DelayFunction) => EventStream<V[]>;
Buffers stream events with given delay. The buffer is flushed at most once in the given interval. So, if your input contains [1,2,3,4,5,6,7], then you might get two events containing [1,2,3,4] and [5,6,7] respectively, given that the flush occurs between numbers 4 and 5.
Also works with a given "defer-function" instead of a delay. Here's a simple example, which is equivalent to stream.bufferWithTime(10):
```js stream.bufferWithTime(function(f) { setTimeout(f, 10) }) ```
Parameter delay
buffer duration in milliseconds
method bufferWithTimeOrCount
bufferWithTimeOrCount: ( delay?: number | DelayFunction, count?: number) => EventStream<V[]>;
Buffers stream events and flushes when either the buffer contains the given number elements or the given amount of milliseconds has passed since last buffered event.
Parameter delay
in milliseconds or as a function
Parameter count
maximum buffer size
method changes
changes: () => EventStream<V>;
method concat
concat: { (other: Observable<V>, options?: EventStreamOptions): EventStream<V>; <V2>(other: Observable<V2>, options?: EventStreamOptions): EventStream< V | V2 >;};
Concatenates two streams/properties into one stream/property so that it will deliver events from this observable until it ends and then deliver events from
other
. This means too that events fromother
, occurring before the end of this observable will not be included in the result stream/property.
method flatMap
flatMap: <V2>(f: SpawnerOrObservable<V, V2>) => EventStream<V2>;
For each element in the source stream, spawn a new stream/property using the function
f
. Collect events from each of the spawned streams into the result stream/property. Note that instead of a function, you can provide a stream/property too. Also, the return value of functionf
can be either anObservable
(stream/property) or a constant value.stream.flatMap()
can be used conveniently with [Bacon.once()
](../globals.html#once) and [Bacon.never()
](../globals.html#never) for converting and filtering at the same time, including only some of the results.Example - converting strings to integers, skipping empty values:
```js stream.flatMap(function(text) { return (text != "") ? parseInt(text) : Bacon.never() }) ```
method flatMapConcat
flatMapConcat: <V2>(f: SpawnerOrObservable<V, V2>) => EventStream<V2>;
A [
flatMapWithConcurrencyLimit
](#flatmapwithconcurrencylimit) with limit of 1.
method flatMapError
flatMapError: <V2>( f: Function1<any, Observable<V2> | EventOrValue<V2>>) => EventStream<V | V2>;
Like [
flatMap
](#flatmap), but is applied only on [Error
](error.html) events. Returned values go into the value stream, unless an error event is returned. As an example, one type of error could result in a retry and another just passed through, which can be implemented using flatMapError.
method flatMapEvent
flatMapEvent: <V2>(f: EventSpawner<V, V2>) => EventStream<V2>;
method flatMapFirst
flatMapFirst: <V2>(f: SpawnerOrObservable<V, V2>) => EventStream<V2>;
Like [
flatMap
](#observable-flatmap), but only spawns a new stream if the previously spawned stream has ended.
method flatMapLatest
flatMapLatest: <V2>(f: SpawnerOrObservable<V, V2>) => EventStream<V2>;
Like [
flatMap
](#flatmap), but instead of including events from all spawned streams, only includes them from the latest spawned stream. You can think this as switching from stream to stream. Note that instead of a function, you can provide a stream/property too.
method flatMapWithConcurrencyLimit
flatMapWithConcurrencyLimit: <V2>( limit: number, f: SpawnerOrObservable<V, V2>) => EventStream<V2>;
A super method of *flatMap* family. It limits the number of open spawned streams and buffers incoming events. [
flatMapConcat
](#flatmapconcat) isflatMapWithConcurrencyLimit(1)
(only one input active), and [flatMap
](#flatmap) isflatMapWithConcurrencyLimit ∞
(all inputs are piped to output).
method flatScan
flatScan: <V2>(seed: V2, f: Function2<V2, V, Observable<V2>>) => Property<V2>;
Scans stream with given seed value and accumulator function, resulting to a Property. Difference to [
scan
](#scan) is that the functionf
can return an [EventStream
](eventstream.html) or a [Property
](property.html) instead of a pure value, meaning that you can use [flatScan
](#flatscan) for asynchronous updates of state. It serializes updates so that that the next update will be queued until the previous one has completed.Parameter seed
initial value to start with
Parameter f
transition function from previous state and new value to next state
method groupBy
groupBy: <V2 = V>( keyF: Function1<V, string>, limitF?: GroupTransformer<V, V2>) => EventStream<EventStream<V2>>;
Groups stream events to new streams by
keyF
. OptionallimitF
can be provided to limit grouped stream life. Stream transformed bylimitF
is passed on if provided.limitF
gets grouped stream and the original event causing the stream to start as parameters.Calculator for grouped consecutive values until group is cancelled:
``` var events = [ {id: 1, type: "add", val: 3 }, {id: 2, type: "add", val: -1 }, {id: 1, type: "add", val: 2 }, {id: 2, type: "cancel"}, {id: 3, type: "add", val: 2 }, {id: 3, type: "cancel"}, {id: 1, type: "add", val: 1 }, {id: 1, type: "add", val: 2 }, {id: 1, type: "cancel"} ]
function keyF(event) { return event.id }
function limitF(groupedStream, groupStartingEvent) { var cancel = groupedStream.filter(function(x) { return x.type === "cancel"}).take(1) var adds = groupedStream.filter(function(x) { return x.type === "add" }) return adds.takeUntil(cancel).map(".val") }
Bacon.sequentially(2, events) .groupBy(keyF, limitF) .flatMap(function(groupedStream) { return groupedStream.fold(0, function(acc, x) { return acc + x }) }) .onValue(function(sum) { console.log(sum) // returns [-1, 2, 8] in an order }) ```
method map
map: { <V2>(f: Function1<V, V2>): EventStream<V2>; <V2>(f: V2 | Property<V2>): EventStream<V2>;};
method merge
merge: { (other: EventStream<V>): EventStream<V>; <V2>(other: EventStream<V2>): EventStream<V | V2>;};
Merges two streams into one stream that delivers events from both
method not
not: () => EventStream<boolean>;
Returns a stream/property that inverts boolean values (using
!
)
method startWith
startWith: (seed: V) => EventStream<V>;
Adds a starting value to the stream/property, i.e. concats a single-element stream containing the single seed value with this stream.
method subscribeInternal
subscribeInternal: (sink?: EventSink<V>) => Unsub;
method toEventStream
toEventStream: () => this;
Returns this stream.
method toProperty
toProperty: (initValue?: V) => Property<V>;
Creates a Property based on the EventStream.
Without arguments, you'll get a Property without an initial value. The Property will get its first actual value from the stream, and after that it'll always have a current value.
You can also give an initial value that will be used as the current value until the first value comes from the stream.
method transform
transform: <V2>(transformer: Transformer<V, V2>, desc?: Desc) => EventStream<V2>;
method transformChanges
transformChanges: (desc: Desc, f: EventStreamDelay<V>) => this;
method withLatestFrom
withLatestFrom: <V2, R>( samplee: Observable<V2>, f: Function2<V, V2, R>) => EventStream<R>;
Creates an EventStream/Property by sampling a given
samplee
stream/property value at each event from the this stream/property.Parameter samplee
Parameter f
function to select/calculate the result value based on the value in the source stream and the samplee
method withStateMachine
withStateMachine: <State, Out>( initState: State, f: StateF<V, State, Out>) => EventStream<Out>;
Lets you run a state machine on an observable. Give it an initial state object and a state transformation function that processes each incoming event and returns an array containing the next state and an array of output events. Here's an example where we calculate the total sum of all numbers in the stream and output the value on stream end:
```js Bacon.fromArray([1,2,3]) .withStateMachine(0, function(sum, event) { if (event.hasValue) return [sum + event.value, []] else if (event.isEnd) return [undefined, [new Bacon.Next(sum), event]] else return [sum, [event]] }) ```
Parameter initState
initial state for the state machine
Parameter f
the function that defines the state machine
class Initial
class Initial<V> extends Value<V> {}
An event carrying the initial value of a [Property](classes/property.html). This event can be emitted by a property immediately when subscribing to it.
Can be distinguished from other events using [isInitial](../globals.html#isinitial)
constructor
constructor(value: {});
property isInitial
isInitial: boolean;
method apply
apply: <V2>(value: V2) => Initial<V2>;
method toNext
toNext: () => Next<V>;
class Next
class Next<V> extends Value<V> {}
Indicates a new value in an [EventStream](eventstream.html) or a [Property](property.html).
Can be distinguished from other events using [isNext](../globals.html#isnext)
constructor
constructor(value: {});
property isNext
isNext: boolean;
method apply
apply: <V2>(value: V2) => Next<V2>;
class Observable
abstract class Observable<V> {}
Observable is the base class for [EventsStream](eventstream.html) and [Property](property.html)
constructor
constructor(desc: Desc);
property desc
desc: Desc;
Contains a structured version of what [
toString
](#tostring) returns. The structured description is an object that contains the fieldscontext
,method
andargs
. For example, forBacon.fromArray([1,2,3]).desc
you'd get{ context: "Bacon", method: "fromArray", args: [[1,2,3]] }
property id
id: number;
Unique numeric id of this Observable. Implemented using a simple counter starting from 1.
property initialDesc
initialDesc: Desc;
method awaiting
awaiting: (other: Observable<any>) => Property<boolean>;
Creates a Property that indicates whether
observable
is awaitingotherObservable
, i.e. has produced a value after the latest value fromotherObservable
. This is handy for keeping track whether we are currently awaiting an AJAX response:```js var showAjaxIndicator = ajaxRequest.awaiting(ajaxResponse) ```
method bufferingThrottle
bufferingThrottle: (minimumInterval: number) => this;
Throttles the observable using a buffer so that at most one value event in minimumInterval is issued. Unlike [
throttle
](#observable-throttle), it doesn't discard the excessive events but buffers them instead, outputting them with a rate of at most one value per minimumInterval.Example:
```js var throttled = source.bufferingThrottle(2) ```
``` source: asdf----asdf---- throttled: a-s-d-f-a-s-d-f- ```
method changes
abstract changes: () => EventStream<V>;
Creates a stream of changes to the Property. The stream *does not* include an event for the current value of the Property at the time this method was called. For EventStreams, this method returns the stream itself.
method combine
combine: <V2, R>(right: Observable<V2>, f: Function2<V, V2, R>) => Property<R>;
Combines the latest values of the two streams or properties using a two-arg function. Similarly to [
scan
](#scan), you can use a method name instead, so you could doa.combine(b, ".concat")
for two properties with array value. The result is a [Property](property.html).
method concat
abstract concat: { (other: Observable<V>): Observable<V>; <V2>(other: Observable<V2>): Observable<V | V2>;};
Concatenates two streams/properties into one stream/property so that it will deliver events from this observable until it ends and then deliver events from
other
. This means too that events fromother
, occurring before the end of this observable will not be included in the result stream/property.
method debounce
debounce: (minimumInterval: number) => this;
Throttles stream/property by given amount of milliseconds, but so that event is only emitted after the given "quiet period". Does not affect emitting the initial value of a [Property](property.html). The difference of [
throttle
](#throttle) and [debounce
](#debounce) is the same as it is in the same methods in jQuery.Example:
``` source: asdf----asdf---- source.debounce(2): -----f-------f-- ```
method debounceImmediate
debounceImmediate: (minimumInterval: number) => this;
Passes the first event in the stream through, but after that, only passes events after a given number of milliseconds have passed since previous output.
Example:
``` source: asdf----asdf---- source.debounceImmediate(2): a-d-----a-d----- ```
method decode
decode: <T extends Record<any, any>>(cases: T) => Property<DecodedValueOf<T>>;
Decodes input using the given mapping. Is a bit like a switch-case or the decode function in Oracle SQL. For example, the following would map the value 1 into the string "mike" and the value 2 into the value of the
who
property.```js property.decode({1 : "mike", 2 : who}) ```
This is actually based on [
combineTemplate
](#combinetemplate) so you can compose static and dynamic data quite freely, as in```js property.decode({1 : { type: "mike" }, 2 : { type: "other", whoThen : who }}) ```
The return value of [
decode
](#decode) is always a [Property
](property.html).
method delay
delay: (delayMs: number) => this;
Delays the stream/property by given amount of milliseconds. Does not delay the initial value of a [
Property
](property.html).```js var delayed = source.delay(2) ```
``` source: asdf----asdf---- delayed: --asdf----asdf-- ```
method deps
deps: () => Observable<any>[];
Returns the an array of dependencies that the Observable has. For instance, for
a.map(function() {}).deps()
, would return[a]
. This method returns the "visible" dependencies only, skipping internal details. This method is thus suitable for visualization tools. Internally, many combinator functions depend on other combinators to create intermediate Observables that the result will actually depend on. Thedeps
method will skip these internal dependencies. See also: [internalDeps](#internaldeps)
method diff
diff: <V2>(start: V, f: Differ<V, V2>) => Property<V2>;
Returns a Property that represents the result of a comparison between the previous and current value of the Observable. For the initial value of the Observable, the previous value will be the given start.
Example:
```js var distance = function (a,b) { return a - b } Bacon.sequentially(1, [1,2,3]).diff(0, distance) ```
This would result to following elements in the result stream:
0 - 1 = -1 1 - 2 = -1 2 - 3 = -1
method doAction
doAction: (f: Function1<V, any>) => this;
Returns a stream/property where the function f is executed for each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the
preventDefault()
method for events. In fact, you can also use a property-extractor string instead of a function, as in".preventDefault"
.Please note that for Properties, it's not guaranteed that the function will be called exactly once per event; when a Property loses all of its subscribers it will re-emit its current value when a new subscriber is added.
method doEnd
doEnd: (f: Function0<any>) => this;
method doError
doError: (f: Function1<any, any>) => this;
Returns a stream/property where the function f is executed for each error, before dispatching to subscribers. That is, same as [
doAction
](#observable-doaction) but for errors.
method doLog
doLog: (...args: any[]) => this;
Logs each value of the Observable to the console. doLog() behaves like [
log
](#log) but does not subscribe to the event stream. You can think of doLog() as a logger function that – unlike log() – is safe to use in production. doLog() is safe, because it does not cause the same surprising side-effects as log() does.
method endAsValue
endAsValue: () => Observable<{}>;
method endOnError
endOnError: (predicate?: Predicate<any>) => this;
Returns a stream/property that ends the on first [
Error
](error.html) event. The error is included in the output of the returned Observable.Parameter predicate
optional predicate function to determine whether to end on a given error
method errors
errors: () => this;
Returns a stream containing [
Error
](error.html) events only. Same as filtering with a function that always returns false.
method filter
filter: (f: Predicate<V> | boolean | Property<boolean>) => this;
Filters values using given predicate function. Instead of a function, you can use a constant value (
true
to include all,false
to exclude all).You can also filter values based on the value of a property. Event will be included in output [if and only if](http://en.wikipedia.org/wiki/If_and_only_if) the property holds
true
at the time of the event.
method first
first: () => this;
Takes the first element from the stream. Essentially
observable.take(1)
.
method firstToPromise
firstToPromise: (PromiseCtr?: Function) => Promise<V>;
Returns a Promise which will be resolved with the first event coming from an Observable. Like [
toPromise
](#topromise), the global ES6 promise implementation will be used unless a promise constructor is given.
method flatMap
abstract flatMap: <V2>(f: SpawnerOrObservable<V, V2>) => Observable<V2>;
For each element in the source stream, spawn a new stream/property using the function
f
. Collect events from each of the spawned streams into the result stream/property. Note that instead of a function, you can provide a stream/property too. Also, the return value of functionf
can be either anObservable
(stream/property) or a constant value.stream.flatMap()
can be used conveniently with [Bacon.once()
](../globals.html#once) and [Bacon.never()
](../globals.html#never) for converting and filtering at the same time, including only some of the results.Example - converting strings to integers, skipping empty values:
```js stream.flatMap(function(text) { return (text != "") ? parseInt(text) : Bacon.never() }) ```
method flatMapConcat
abstract flatMapConcat: <V2>(f: SpawnerOrObservable<V, V2>) => Observable<V2>;
A [
flatMapWithConcurrencyLimit
](#flatmapwithconcurrencylimit) with limit of 1.
method flatMapError
abstract flatMapError: <V2>( f: Function1<any, Observable<V2> | EventOrValue<V2>>) => Observable<V | V2>;
Like [
flatMap
](#flatmap), but is applied only on [Error
](error.html) events. Returned values go into the value stream, unless an error event is returned. As an example, one type of error could result in a retry and another just passed through, which can be implemented using flatMapError.
method flatMapEvent
abstract flatMapEvent: <V2>(f: EventSpawner<V, V2>) => Observable<V2>;
method flatMapFirst
abstract flatMapFirst: <V2>(f: SpawnerOrObservable<V, V2>) => Observable<V2>;
Like [
flatMap
](#observable-flatmap), but only spawns a new stream if the previously spawned stream has ended.
method flatMapLatest
abstract flatMapLatest: <V2>(f: SpawnerOrObservable<V, V2>) => Observable<V2>;
Like [
flatMap
](#flatmap), but instead of including events from all spawned streams, only includes them from the latest spawned stream. You can think this as switching from stream to stream. Note that instead of a function, you can provide a stream/property too.
method flatMapWithConcurrencyLimit
abstract flatMapWithConcurrencyLimit: <V2>( limit: number, f: SpawnerOrObservable<V, V2>) => Observable<V2>;
A super method of *flatMap* family. It limits the number of open spawned streams and buffers incoming events. [
flatMapConcat
](#flatmapconcat) isflatMapWithConcurrencyLimit(1)
(only one input active), and [flatMap
](#flatmap) isflatMapWithConcurrencyLimit ∞
(all inputs are piped to output).
method fold
fold: <V2>(seed: V2, f: Accumulator<V, V2>) => Property<V2>;
Works like [
scan
](#scan) but only emits the final value, i.e. the value just before the observable ends. Returns a [Property
](property.html).
method forEach
forEach: (f?: Sink<V>) => Unsub;
An alias for [onValue](#onvalue).
Subscribes a given handler function to the observable. Function will be called for each new value (not for errors or stream end).
method groupBy
abstract groupBy: <V2 = V>( keyF: Function1<V, string>, limitF?: GroupTransformer<V, V2>) => Observable<EventStream<V2>>;
Groups stream events to new streams by
keyF
. OptionallimitF
can be provided to limit grouped stream life. Stream transformed bylimitF
is passed on if provided.limitF
gets grouped stream and the original event causing the stream to start as parameters.Calculator for grouped consecutive values until group is cancelled:
``` var events = [ {id: 1, type: "add", val: 3 }, {id: 2, type: "add", val: -1 }, {id: 1, type: "add", val: 2 }, {id: 2, type: "cancel"}, {id: 3, type: "add", val: 2 }, {id: 3, type: "cancel"}, {id: 1, type: "add", val: 1 }, {id: 1, type: "add", val: 2 }, {id: 1, type: "cancel"} ]
function keyF(event) { return event.id }
function limitF(groupedStream, groupStartingEvent) { var cancel = groupedStream.filter(function(x) { return x.type === "cancel"}).take(1) var adds = groupedStream.filter(function(x) { return x.type === "add" }) return adds.takeUntil(cancel).map(".val") }
Bacon.sequentially(2, events) .groupBy(keyF, limitF) .flatMap(function(groupedStream) { return groupedStream.fold(0, function(acc, x) { return acc + x }) }) .onValue(function(sum) { console.log(sum) // returns [-1, 2, 8] in an order }) ```
method holdWhen
holdWhen: (valve: Property<boolean>) => EventStream<V>;
Pauses and buffers the event stream if last event in valve is truthy. All buffered events are released when valve becomes falsy.
method inspect
inspect: () => string;
method internalDeps
internalDeps: () => any[];
Returns the true dependencies of the observable, including the intermediate "hidden" Observables. This method is for Bacon.js internal purposes but could be useful for debugging/analysis tools as well. See also: [deps](#deps)
method last
last: () => this;
Takes the last element from the stream. None, if stream is empty.
Note:*
neverEndingStream.last()
creates the stream which doesn't produce any events and never ends.
method log
log: (...args: any[]) => this;
Logs each value of the Observable to the console. It optionally takes arguments to pass to console.log() alongside each value. To assist with chaining, it returns the original Observable. Note that as a side-effect, the observable will have a constant listener and will not be garbage-collected. So, use this for debugging only and remove from production code. For example:
```js myStream.log("New event in myStream") ```
or just
```js myStream.log() ```
method map
abstract map: <V2>(f: Function1<V, V2> | Property<V2> | V2) => Observable<V2>;
Maps values using given function, returning a new stream/property. Instead of a function, you can also provide a [Property](property.html), in which case each element in the source stream will be mapped to the current value of the given property.
method mapEnd
mapEnd: (f: Function0<V> | V) => this;
Adds an extra [
Next
](next.html) event just before End. The value is created by calling the given function when the source stream ends. Instead of a function, a static value can be used.
method mapError
mapError: (f: Function1<any, V> | V) => this;
Maps errors using given function. More specifically, feeds the "error" field of the error event to the function and produces a [
Next
](next.html) event based on the return value.
method name
name: (name: string) => this;
Sets the name of the observable. Overrides the default implementation of [
toString
](#tostring) andinspect
. Returns the same observable, with mutated name.
method not
abstract not: () => Observable<boolean>;
Returns a stream/property that inverts boolean values (using
!
)
method onEnd
onEnd: (f?: VoidSink) => Unsub;
Subscribes a callback to stream end. The function will be called when the stream ends. Just like
subscribe
, this method returns a function for unsubscribing.
method onError
onError: (f?: Sink<any>) => Unsub;
Subscribes a handler to error events. The function will be called for each error in the stream. Just like
subscribe
, this method returns a function for unsubscribing.
method onValue
onValue: (f?: Sink<V>) => Unsub;
Subscribes a given handler function to the observable. Function will be called for each new value. This is the simplest way to assign a side-effect to an observable. The difference to the
subscribe
method is that the actual stream values are received, instead of [Event
](event) objects. Just likesubscribe
, this method returns a function for unsubscribing.stream.onValue
andproperty.onValue
behave similarly, except that the latter also pushes the initial value of the property, in case there is one.
method onValues
onValues: (f: Function) => Unsub;
Like [
onValue
](#onvalue), but splits the value (assuming its an array) as function arguments tof
. Only applicable for observables with arrays as values.
method reduce
reduce: <V2>(seed: V2, f: Accumulator<V, V2>) => Property<V2>;
A synonym for [fold](#fold).
method sampledBy
sampledBy: { (sampler: EventStream<any>): EventStream<V>; (sampler: Property<any>): Property<V>; (sampler: Observable<any>): Observable<V>;};
Creates an EventStream/Property by sampling this stream/property value at each event from the
sampler
stream. The result will contain the sampled value at each event in the source stream.Parameter sampler
method scan
scan: <V2>(seed: V2, f: Accumulator<V, V2>) => Property<V2>;
Scans stream/property with given seed value and accumulator function, resulting to a Property. For example, you might use zero as seed and a "plus" function as the accumulator to create an "integral" property. Instead of a function, you can also supply a method name such as ".concat", in which case this method is called on the accumulator value and the new stream value is used as argument.
Example:
```js var plus = function (a,b) { return a + b } Bacon.sequentially(1, [1,2,3]).scan(0, plus) ```
This would result to following elements in the result stream:
seed value = 0 0 + 1 = 1 1 + 2 = 3 3 + 3 = 6
When applied to a Property as in
r = p.scan(seed, f)
, there's a (hopefully insignificant) catch: The starting value forr
depends on whetherp
has an initial value when scan is applied. If there's no initial value, this works identically to EventStream.scan: theseed
will be the initial value ofr
. However, ifr
already has a current/initial valuex
, the seed won't be output as is. Instead, the initial value ofr
will bef(seed, x)
. This makes sense, because there can only be 1 initial value for a Property at a time.
method skip
skip: (count: number) => this;
Skips the first n elements from the stream
method skipDuplicates
skipDuplicates: (isEqual?: Equals<V>) => this;
Drops consecutive equal elements. So, from
[1, 2, 2, 1]
you'd get[1, 2, 1]
. Uses the===
operator for equality checking by default. If the isEqual argument is supplied, checks by calling isEqual(oldValue, newValue). For instance, to do a deep comparison,you can use the isEqual function from [underscore.js](http://underscorejs.org/) likestream.skipDuplicates(_.isEqual)
.
method skipErrors
skipErrors: () => this;
Returns a new stream/property which excludes all [Error](error.html) events in the source
method skipUntil
skipUntil: (starter: Observable<any>) => this;
Skips elements from the source, until a value event appears in the given
starter
stream/property. In other words, starts delivering values from the source after first value appears instarter
.
method skipWhile
skipWhile: (f: PredicateOrProperty<V>) => this;
Skips elements until the given predicate function returns falsy once, and then lets all events pass through. Instead of a predicate you can also pass in a
Property<boolean>
to skip elements while the Property holds a truthy value.
method slidingWindow
slidingWindow: (maxValues: number, minValues?: number) => Property<V[]>;
Returns a Property that represents a "sliding window" into the history of the values of the Observable. The result Property will have a value that is an array containing the last
n
values of the original observable, wheren
is at most the value of themax
argument, and at least the value of themin
argument. If themin
argument is omitted, there's no lower limit of values.For example, if you have a stream
s
with value a sequence 1 - 2 - 3 - 4 - 5, the respective values ins.slidingWindow(2)
would be [] - [1] - [1,2] - [2,3] - [3,4] - [4,5]. The values ofs.slidingWindow(2,2)
would be [1,2] - [2,3] - [3,4] - [4,5].
method startWith
abstract startWith: (seed: V) => Observable<V>;
Adds a starting value to the stream/property, i.e. concats a single-element stream containing the single seed value with this stream.
method subscribe
subscribe: (sink?: EventSink<V>) => Unsub;
subscribes given handler function to event stream. Function will receive [event](event.html) objects for all new value, end and error events in the stream. The subscribe() call returns a
unsubscribe
function that you can call to unsubscribe. You can also unsubscribe by returning [Bacon.noMore
](../globals.html#nomore) from the handler function as a reply to an Event.stream.subscribe
andproperty.subscribe
behave similarly, except that the latter also pushes the initial value of the property, in case there is one.Parameter sink
the handler function
Returns
{Unsub}
method subscribeInternal
abstract subscribeInternal: (sink: EventSink<V>) => Unsub;
method take
take: (count: number) => this;
Takes at most n values from the stream and then ends the stream. If the stream has fewer than n values then it is unaffected. Equal to [
Bacon.never()
](../globals.html#never) ifn <= 0
.
method takeUntil
takeUntil: (stopper: Observable<any>) => this;
Takes elements from source until a value event appears in the other stream. If other stream ends without value, it is ignored.
method takeWhile
takeWhile: (f: PredicateOrProperty<V>) => this;
Takes while given predicate function holds true, and then ends. Alternatively, you can supply a boolean Property to take elements while the Property holds
true
.
method throttle
throttle: (minimumInterval: number) => this;
Throttles stream/property by given amount of milliseconds. Events are emitted with the minimum interval of [
delay
](#observable-delay). The implementation is based on [stream.bufferWithTime
](#stream-bufferwithtime). Does not affect emitting the initial value of a [Property
](#property).Example:
```js var throttled = source.throttle(2) ```
``` source: asdf----asdf---- throttled: --s--f----s--f-- ```
method toEventStream
abstract toEventStream: () => EventStream<V>;
method toPromise
toPromise: (PromiseCtr?: Function) => Promise<V>;
Returns a Promise which will be resolved with the last event coming from an Observable. The global ES6 promise implementation will be used unless a promise constructor is given. Use a shim if you need to support legacy browsers or platforms. [caniuse promises](http://caniuse.com/#feat=promises).
See also [firstToPromise](#firsttopromise).
method toProperty
abstract toProperty: () => Property<V>;
In case of EventStream, creates a Property based on the EventStream.
In case of Property, returns the Property itself.
method toString
toString: () => string;
Returns a textual description of the Observable. For instance,
Bacon.once(1).map(function() {}).toString()
would return "Bacon.once(1).map(function)".
method transform
abstract transform: <V2>( transformer: Transformer<V, V2>, desc?: Desc) => Observable<V2>;
TODO: proper documentation missing Lets you do more custom event handling: you get all events to your function and you can output any number of events and end the stream if you choose. For example, to send an error and end the stream in case a value is below zero:
```js if (Bacon.hasValue(event) && event.value < 0) { sink(new Bacon.Error("Value below zero")); return sink(end()); } else { return sink(event); } ```
Note that it's important to return the value from
sink
so that the connection to the underlying stream will be closed when no more events are needed.
method transformChanges
abstract transformChanges: (desc: Desc, f: EventStreamDelay<V>) => this;
method withDesc
withDesc: (desc?: Desc) => this;
method withDescription
withDescription: (context: any, method: string, ...args: any[]) => this;
Sets the structured description of the observable. The [
toString
](#tostring) andinspect
methods use this data recursively to create a string representation for the observable. This method is probably useful for Bacon core / library / plugin development only.For example:
var src = Bacon.once(1) var obs = src.map(function(x) { return -x }) console.log(obs.toString()) --> Bacon.once(1).map(function) obs.withDescription(src, "times", -1) console.log(obs.toString()) --> Bacon.once(1).times(-1)
The method returns the same observable with mutated description.
method withLatestFrom
abstract withLatestFrom: <V2, R>( samplee: Observable<V2>, f: Function2<V, V2, R>) => Observable<R>;
Creates an EventStream/Property by sampling a given
samplee
stream/property value at each event from the this stream/property.Parameter samplee
Parameter f
function to select/calculate the result value based on the value in the source stream and the samplee
method withStateMachine
abstract withStateMachine: <State, Out>( initState: State, f: StateF<V, State, Out>) => Observable<Out>;
Lets you run a state machine on an observable. Give it an initial state object and a state transformation function that processes each incoming event and returns an array containing the next state and an array of output events. Here's an example where we calculate the total sum of all numbers in the stream and output the value on stream end:
```js Bacon.fromArray([1,2,3]) .withStateMachine(0, function(sum, event) { if (event.hasValue) return [sum + event.value, []] else if (event.isEnd) return [undefined, [new Bacon.Next(sum), event]] else return [sum, [event]] }) ```
Parameter initState
initial state for the state machine
Parameter f
the function that defines the state machine
method zip
zip: <V2, R>(other: Observable<V2>, f: Function2<V, V2, R>) => EventStream<R>;
Returns an EventStream with elements pair-wise lined up with events from this and the other EventStream or Property. A zipped stream will publish only when it has a value from each source and will only produce values up to when any single source ends.
The given function
f
is used to create the result value from value in the two sources. If no function is given, the values are zipped into an array.Be careful not to have too much "drift" between streams. If one stream produces many more values than some other excessive buffering will occur inside the zipped observable.
Example 1:
```js var x = Bacon.fromArray([1, 2]) var y = Bacon.fromArray([3, 4]) x.zip(y, function(x, y) { return x + y })
# produces values 4, 6 ```
See also [
zipWith
](../globals.html#zipwith) and [zipAsArray
](../globals.html/zipasarray) for zipping more than 2 sources.
class Property
class Property<V> extends Observable<V> {}
A reactive property. Has the concept of "current value". You can create a Property from an EventStream by using either [
toProperty
](eventstream.html#toproperty) or [scan
](eventstream.html#scan) method. Note: depending on how a Property is created, it may or may not have an initial value. The current value stays as its last value after the stream has ended.Here are the most common ways for creating Properties:
- Create a constant property with [constant](../globals.html#constant) - Create a property based on an EventStream with [toProperty](eventstream.html#toproperty) - Scan an EventStream with an accumulator function with [scan](eventstream.html#scan) - Create a state property based on multiple sources using [update](../globals.html#update)
constructor
constructor(desc: Desc, subscribe: Subscribe<V>, handler?: EventSink<V>);
method and
and: (other: Property<any>) => Property<boolean>;
Combines properties with the
&&
operator. It produces a new value when either of the Properties change, combining the latest values using&&
.
method changes
changes: () => EventStream<V>;
creates a stream of changes to the Property. The stream *does not* include an event for the current value of the Property at the time this method was called.
method concat
concat: { (other: Observable<V>): Property<V>; <V2>(other: Observable<V2>): Property<V | V2>;};
Concatenates this property with another stream/properties into one property so that it will deliver events from this property it ends and then deliver events from
other
. This means too that events fromother
, occurring before the end of this property will not be included in the result stream/property.
method flatMap
flatMap: <V2>(f: SpawnerOrObservable<V, V2>) => Property<V2>;
For each element in the source stream, spawn a new stream/property using the function
f
. Collect events from each of the spawned streams into the result property. Note that instead of a function, you can provide a stream/property too. Also, the return value of functionf
can be either anObservable
(stream/property) or a constant value.stream.flatMap()
can be used conveniently with [Bacon.once()
](../globals.html#once) and [Bacon.never()
](../globals.html#never) for converting and filtering at the same time, including only some of the results.Example - converting strings to integers, skipping empty values:
```js stream.flatMap(function(text) { return (text != "") ? parseInt(text) : Bacon.never() }) ```
method flatMapConcat
flatMapConcat: <V2>(f: SpawnerOrObservable<V, V2>) => Property<V2>;
A [
flatMapWithConcurrencyLimit
](#flatmapwithconcurrencylimit) with limit of 1.
method flatMapError
flatMapError: <V2>( f: Function1<any, Observable<V2> | EventOrValue<V2>>) => Property<V | V2>;
Like [
flatMap
](#flatmap), but is applied only on [Error
](error.html) events. Returned values go into the value stream, unless an error event is returned. As an example, one type of error could result in a retry and another just passed through, which can be implemented using flatMapError.
method flatMapEvent
flatMapEvent: <V2>(f: EventSpawner<V, V2>) => Property<V2>;
method flatMapFirst
flatMapFirst: <V2>(f: SpawnerOrObservable<V, V2>) => Property<V2>;
Like [
flatMap
](#observable-flatmap), but only spawns a new stream if the previously spawned stream has ended.
method flatMapLatest
flatMapLatest: <V2>(f: SpawnerOrObservable<V, V2>) => Property<V2>;
Like [
flatMap
](#flatmap), but instead of including events from all spawned streams, only includes them from the latest spawned stream. You can think this as switching from stream to stream. Note that instead of a function, you can provide a stream/property too.
method flatMapWithConcurrencyLimit
flatMapWithConcurrencyLimit: <V2>( limit: number, f: SpawnerOrObservable<V, V2>) => Property<V2>;
A super method of *flatMap* family. It limits the number of open spawned streams and buffers incoming events. [
flatMapConcat
](#flatmapconcat) isflatMapWithConcurrencyLimit(1)
(only one input active), and [flatMap
](#flatmap) isflatMapWithConcurrencyLimit ∞
(all inputs are piped to output).
method groupBy
groupBy: <V2 = V>( keyF: Function1<V, string>, limitF?: GroupTransformer<V, V2>) => Property<EventStream<V2>>;
Groups stream events to new streams by
keyF
. OptionallimitF
can be provided to limit grouped stream life. Stream transformed bylimitF
is passed on if provided.limitF
gets grouped stream and the original event causing the stream to start as parameters.Calculator for grouped consecutive values until group is cancelled:
``` var events = [ {id: 1, type: "add", val: 3 }, {id: 2, type: "add", val: -1 }, {id: 1, type: "add", val: 2 }, {id: 2, type: "cancel"}, {id: 3, type: "add", val: 2 }, {id: 3, type: "cancel"}, {id: 1, type: "add", val: 1 }, {id: 1, type: "add", val: 2 }, {id: 1, type: "cancel"} ]
function keyF(event) { return event.id }
function limitF(groupedStream, groupStartingEvent) { var cancel = groupedStream.filter(function(x) { return x.type === "cancel"}).take(1) var adds = groupedStream.filter(function(x) { return x.type === "add" }) return adds.takeUntil(cancel).map(".val") }
Bacon.sequentially(2, events) .groupBy(keyF, limitF) .flatMap(function(groupedStream) { return groupedStream.fold(0, function(acc, x) { return acc + x }) }) .onValue(function(sum) { console.log(sum) // returns [-1, 2, 8] in an order }) ```
method map
map: { <V2>(f: Function1<V, V2>): Property<V2>; <V2>(f: V2 | Property<V2>): Property<V2>;};
method not
not: () => Property<boolean>;
Returns a Property that inverts the value of this one (using the
!
operator). *
method or
or: (other: Property<any>) => Property<boolean>;
Combines properties with the
||
operator. It produces a new value when either of the Properties change, combining the latest values using||
.
method sample
sample: (interval: number) => EventStream<V>;
Creates an EventStream by sampling the property value at given interval (in milliseconds)
method startWith
startWith: (seed: V) => Property<V>;
Adds an initial "default" value for the Property. If the Property doesn't have an initial value of it's own, the given value will be used as the initial value. If the property has an initial value of its own, the given value will be ignored.
method subscribeInternal
subscribeInternal: (sink?: EventSink<V>) => Unsub;
method toEventStream
toEventStream: (options?: EventStreamOptions) => EventStream<V>;
Creates an EventStream based on this Property. The stream contains also an event for the current value of this Property at the time this method was called.
method toProperty
toProperty: () => Property<V>;
Returns the Property itself.
method transform
transform: <V2>(transformer: Transformer<V, V2>, desc?: Desc) => Property<V2>;
method transformChanges
transformChanges: (desc: Desc, f: EventStreamDelay<V>) => this;
method withLatestFrom
withLatestFrom: <V2, R>( samplee: Observable<V2>, f: Function2<V, V2, R>) => Property<R>;
Creates an EventStream/Property by sampling a given
samplee
stream/property value at each event from the this stream/property.Parameter samplee
Parameter f
function to select/calculate the result value based on the value in the source stream and the samplee
method withStateMachine
withStateMachine: <State, Out>( initState: State, f: StateF<V, State, Out>) => Property<Out>;
Lets you run a state machine on an observable. Give it an initial state object and a state transformation function that processes each incoming event and returns an array containing the next state and an array of output events. Here's an example where we calculate the total sum of all numbers in the stream and output the value on stream end:
```js Bacon.fromArray([1,2,3]) .withStateMachine(0, function(sum, event) { if (event.hasValue) return [sum + event.value, []] else if (event.isEnd) return [undefined, [new Bacon.Next(sum), event]] else return [sum, [event]] }) ```
Parameter initState
initial state for the state machine
Parameter f
the function that defines the state machine
class Value
abstract class Value<V> extends Event<V> {}
Base class for all [Events](event.html) carrying a value.
Can be distinguished from other events using [hasValue](../globals.html#hasvalue)
constructor
constructor(value: {});
property hasValue
hasValue: boolean;
property value
value: {};
method apply
abstract apply: <V2>(value: V2) => Value<V2>;
method filter
filter: (f: (value: V) => boolean) => boolean;
method fmap
fmap: <V2>(f: (value: V) => V2) => Value<V2>;
method log
log: () => any;
method toString
toString: () => string;
Interfaces
interface RetryContext
interface RetryContext {}
property error
error: any;
property retriesDone
retriesDone: number;
interface RetryOptions
interface RetryOptions<V> {}
Options object for [Bacon.retry](../globals.html#retry).
property retries
retries?: number;
Required. The number of times to retry the
source
function _in addition to the initial attempt_. The default value is 0 (zero) for retrying indefinitely.
property source
source: (attemptNumber: number) => Observable<V>;
Required. A function that produces an Observable. The function gets attempt number (starting from zero) as its argument.
method delay
delay: (context: RetryContext) => number;
Optional. A function that returns the time in milliseconds to wait before retrying. Defaults to
0
. The function is given a context object with the keys ```error``` (the error that occurred) andretriesDone
(the number of retries already performed) to help determine the appropriate delay e.g. for an incremental backoff.
method isRetryable
isRetryable: (error: any) => boolean;
Optional. A function returning
true
to continue retrying,false
to stop. Defaults totrue
. The error that occurred is given as a parameter. For example, there is usually no reason to retry a 404 HTTP error, whereas a 500 or a timeout might work on the next attempt.
Type Aliases
type Binder
type Binder<V> = (sink: FlexibleSink<V>) => Unsub;
Binder function used in [fromBinder](../globals.html#frombinder)
type EventLike
type EventLike<V> = V | Event<V> | Event<V>[];
type EventSink
type EventSink<V> = (event: Event<V>) => Reply;
type EventStreamDelay
type EventStreamDelay<V> = (stream: EventStream<V>) => EventStream<V>;
type EventTransformer
type EventTransformer<V> = (...args: any[]) => EventLike<V>;
type FlexibleSink
type FlexibleSink<V> = (event: EventLike<V>) => Reply;
type Function0
type Function0<R> = () => R;
type Function1
type Function1<T1, R> = (t1: T1) => R;
type Function2
type Function2<T1, T2, R> = (t1: T1, t2: T2) => R;
type Function3
type Function3<T1, T2, T3, R> = (t1: T1, t2: T2, t3: T3) => R;
type Function4
type Function4<T1, T2, T3, T4, R> = (t1: T1, t2: T2, t3: T3, t4: T4) => R;
type Function5
type Function5<T1, T2, T3, T4, T5, R> = ( t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R;
type Function6
type Function6<T1, T2, T3, T4, T5, T6, R> = ( t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6) => R;
type Pattern
type Pattern<O> = | Pattern1<any, O> | Pattern2<any, any, O> | Pattern3<any, any, any, O> | Pattern4<any, any, any, any, O> | Pattern5<any, any, any, any, any, O> | Pattern6<any, any, any, any, any, any, O> | RawPattern;
Join pattern type, allowing up to 6 sources per pattern.
type Pattern1
type Pattern1<I1, O> = [ObservableOrSource<I1>, O | ((a: I1) => O)];
Join pattern consisting of a single EventStream and a mapping function.
type Pattern2
type Pattern2<I1, I2, O> = [ ObservableOrSource<I1>, ObservableOrSource<I1>, O | ((a: I1, b: I2) => O)];
Join pattern consisting of a 2 Observables and a combinator function. At least one of the Observables must be an EventStream.
type Pattern3
type Pattern3<I1, I2, I3, O> = [ ObservableOrSource<I1>, ObservableOrSource<I1>, ObservableOrSource<I3>, O | ((a: I1, b: I2, c: I3) => O)];
Join pattern consisting of a 3 Observables and a combinator function. At least one of the Observables must be an EventStream.
type Pattern4
type Pattern4<I1, I2, I3, I4, O> = [ ObservableOrSource<I1>, ObservableOrSource<I1>, ObservableOrSource<I3>, ObservableOrSource<I4>, O | ((a: I1, b: I2, c: I3, d: I4) => O)];
Join pattern consisting of a 4 Observables and a combinator function. At least one of the Observables must be an EventStream.
type Pattern5
type Pattern5<I1, I2, I3, I4, I5, O> = [ ObservableOrSource<I1>, ObservableOrSource<I1>, ObservableOrSource<I3>, ObservableOrSource<I4>, ObservableOrSource<I5>, O | ((a: I1, b: I2, c: I3, d: I4, e: I5) => O)];
Join pattern consisting of a 5 Observables and a combinator function. At least one of the Observables must be an EventStream.
type Pattern6
type Pattern6<I1, I2, I3, I4, I5, I6, O> = [ ObservableOrSource<I1>, ObservableOrSource<I1>, ObservableOrSource<I3>, ObservableOrSource<I4>, ObservableOrSource<I5>, ObservableOrSource<I6>, O | ((a: I1, b: I2, c: I3, d: I4, e: I5, f: I6) => O)];
Join pattern consisting of a 6 Observables and a combinator function. At least one of the Observables must be an EventStream.
type Reply
type Reply = '<no-more>' | any;
Return type for various [Sink](#sink) functions. Indicates whether or not the sink desires more input from its source. See [
Bacon.fromBinder
](#frombinder) for example.
type Sink
type Sink<V> = (value: V) => Reply;
type Spy
type Spy = (obs: Observable<any>) => any;
type Subscribe
type Subscribe<T> = (arg: EventSink<T>) => Unsub;
type Unsub
type Unsub = () => void;
an "unsubscribe" function returned by [subscribe](classes/Observable.html#subscribe) et al. You can cancel your subscription by calling this function.
type UpdatePattern
type UpdatePattern<O> = | UpdatePattern1<any, O> | UpdatePattern2<any, any, O> | UpdatePattern3<any, any, any, O> | UpdatePattern4<any, any, any, any, O> | UpdatePattern5<any, any, any, any, any, O> | UpdatePattern6<any, any, any, any, any, any, O>;
[Update](#update) pattern type, allowing up to 6 sources per pattern.
type UpdatePattern1
type UpdatePattern1<I1, O> = [Observable<I1>, O | ((acc: O, a: I1) => O)];
[Update](#update) pattern consisting of a single EventStream and a accumulator function.
type UpdatePattern2
type UpdatePattern2<I1, I2, O> = [ Observable<I1>, Observable<I1>, O | ((acc: O, a: I1, b: I2) => O)];
[Update](#update) pattern consisting of 2 Observables and an accumulrator function. At least one of the Observables must be an EventStream.
type UpdatePattern3
type UpdatePattern3<I1, I2, I3, O> = [ Observable<I1>, Observable<I1>, Observable<I3>, O | ((acc: O, a: I1, b: I2, c: I3) => O)];
[Update](#update) pattern consisting of 3 Observables and an accumulrator function. At least one of the Observables must be an EventStream.
type UpdatePattern4
type UpdatePattern4<I1, I2, I3, I4, O> = [ Observable<I1>, Observable<I1>, Observable<I3>, Observable<I4>, O | ((acc: O, a: I1, b: I2, c: I3, d: I4) => O)];
[Update](#update) pattern consisting of 4 Observables and an accumulrator function. At least one of the Observables must be an EventStream.
type UpdatePattern5
type UpdatePattern5<I1, I2, I3, I4, I5, O> = [ Observable<I1>, Observable<I1>, Observable<I3>, Observable<I4>, Observable<I5>, O | ((acc: O, a: I1, b: I2, c: I3, d: I4, e: I5) => O)];
[Update](#update) pattern consisting of 5 Observables and an accumulrator function. At least one of the Observables must be an EventStream.
type UpdatePattern6
type UpdatePattern6<I1, I2, I3, I4, I5, I6, O> = [ Observable<I1>, Observable<I1>, Observable<I3>, Observable<I4>, Observable<I5>, Observable<I6>, O | ((acc: O, a: I1, b: I2, c: I3, d: I4, e: I5, f: I6) => O)];
[Update](#update) pattern consisting of 6 Observables and an accumulrator function. At least one of the Observables must be an EventStream.
type VoidSink
type VoidSink = () => Reply;
Package Files (38)
- types/bacon.d.ts
- types/bus.d.ts
- types/callback.d.ts
- types/combine.d.ts
- types/combinetemplate.d.ts
- types/compositeunsubscribe.d.ts
- types/concat.d.ts
- types/constant.d.ts
- types/describe.d.ts
- types/event.d.ts
- types/fromarray.d.ts
- types/frombinder.d.ts
- types/fromesobservable.d.ts
- types/fromevent.d.ts
- types/frompoll.d.ts
- types/frompromise.d.ts
- types/groupsimultaneous.d.ts
- types/interval.d.ts
- types/jquery.d.ts
- types/later.d.ts
- types/merge.d.ts
- types/never.d.ts
- types/observable.d.ts
- types/once.d.ts
- types/onvalues.d.ts
- types/repeat.d.ts
- types/repeatedly.d.ts
- types/reply.d.ts
- types/retry.d.ts
- types/scheduler.d.ts
- types/sequentially.d.ts
- types/silence.d.ts
- types/spy.d.ts
- types/try.d.ts
- types/types.d.ts
- types/update.d.ts
- types/when.d.ts
- types/zip.d.ts
Dependencies (0)
No dependencies.
Dev Dependencies (32)
- @rollup/plugin-replace
- @types/bluebird
- @types/chai
- @types/mocha
- @types/node
- @types/sinon
- @types/zen-observable
- benchmark
- bluebird
- browserify
- browserstack-runner
- chai
- es6-promise
- escodegen
- esm
- esprima
- estraverse
- jquery
- jsstana
- mocha
- nodemon
- rollup
- rollup-plugin-typescript2
- rxjs
- sinon
- terser
- ts-node
- tsify
- typedoc
- typescript
- uglify-js
- zen-observable
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/baconjs
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/baconjs)
- HTML<a href="https://www.jsdocs.io/package/baconjs"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 7372 ms. - Missing or incorrect documentation? Open an issue for this package.