Skip to content

Instantly share code, notes, and snippets.

@aanand
Last active December 15, 2015 04:59
Show Gist options
  • Save aanand/5206145 to your computer and use it in GitHub Desktop.
Save aanand/5206145 to your computer and use it in GitHub Desktop.
Combining two streams in Bacon.js, but only updating when one stream updates

Say I have two properties, a and b. If I want a stream that combines their values, I can use a.combine(b, <fn>). Abstractly, this gets me the following:

a:      0    1              2
b:      0         1    2         3
a,b:    0,0  1,0  1,1  1,2  2,2  2,3

But what I need is a stream that only updates when a updates, but uses the most up-to-date value of b. That is:

a:      0    1              2
b:      0         1    2         3
a,b:    0,0  1,0            2,2

Furthermore, successive values of a may be equal, and I don't want to skip duplicates, so I want:

a:      0    1              1
b:      0         1    2         3
a,b:    0,0  1,0            1,2

How would I build this?

@raimohanska
Copy link

b.sampledBy(a, function(b, a) { return a + "," + b }) should do.

It outputs a value on each event in stream a, and combines it with the latest value of b using your custom function.

@aanand
Copy link
Author

aanand commented Mar 21, 2013

@raimohanska Perfect, thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment