0

my_Stream is data I want to accumulate and assign to variable for further processing. My question: How do I get the contents of the variable the_string to console.log ONCE THE STREAM IS FINISHED?

my_Stream.onValue(function(value) {
 the_string = the_string.concat(value);
});

My full code can be found in github issue page: github.com/nodeschool/discussions/issues/1778

nogo10
  • 3
  • 2

1 Answers1

1

What you want to use is fold, which scans the stream and outputs a value only when the stream ends.

const stream = Bacon.sequentially(100, ["Hello", "world"])    
stream.log("stream")
const concatenated = stream.fold("", (a,b) => a + b)
concatenated.log("concatenated")

http://jsbin.com/yodudiqovi/edit?html,js,console

OlliM
  • 7,023
  • 1
  • 36
  • 47
  • In jsbin it works but doesn't pass the unit test . To give a bit of context, I created the stream using Bacon.fromBinder as a buffer for a http request, response. Yes I might have used a simpler buffer lib (eg. bl.js). Using Bacon.js as a buffer seems like overkill. What's frustrating is that onValue() works to log() the contents of the stream but doesn't allow chaining to fold(). – nogo10 Jun 28 '16 at 03:35
  • Do you have a working example of your code that you could share? Without seeing the code it's very hard to help you. – OlliM Jun 28 '16 at 08:49
  • Im new to stackoverflow, can't get code formatting right.. so here is the github issue page with my code: https://github.com/nodeschool/discussions/issues/1778 – nogo10 Jun 28 '16 at 11:56
  • I added a comment in the gist, but the problem was that your stream never ends, so the fold never outputs a value. – OlliM Jun 28 '16 at 12:14
  • Yes agreed fold method is the right choice. I was running into errors from your example because I was using Javascript in ES5 syntax which results in an error. `const concatenated = stream.fold("", (a,b) => a + b)` <---works 'var concatenated = stream.fold("", function (a,b){ a + b})` <----does not work I have to assume Bacon.js works more reliably in ES6 syntax – nogo10 Jun 30 '16 at 02:29
  • 1
    You're missing the "return" keyword in your ES5 example. That's why it doesn't work. – raimohanska Jun 30 '16 at 06:43
  • 1
    Sorry, I'm so used to writing ES6 that I didn't even think about using ES5. Actually "Bacon.js works more reliably in ES6 syntax" is not true, but I do recommend using ES6 in Bacon.js, as the shorter function syntax really makes the FRP style code easier to write and read. That's the same reason that @raimohanska wrote Bacon.js in CoffeeScript. – OlliM Jun 30 '16 at 07:10