0

I have 3 streams. (1) gradingResult and contextId are ajax requests that depend on studentResponse. (2) For each studentResponse value, I need to fire an event with the studentResponse value and the corresponding result from the other two streams.

This question is similar but different than Wait for latest values from dependent streams in BaconJS?. One key difference is that I don't know which of gradingResult and contextId will return first.

A note about the code: the code is based on production code. I do not have access to gradingResult or contextId. All I know is that they're ajax requests that take inputs from studentResponse.

Some sample code with desired output:

function _fauxAjax(val) {
  return Bacon.fromBinder(function(sink) {
    setTimeout(function() { 
        sink(val); 
        sink(new Bacon.End());
    }, Math.random()*1000);
    return function() {}
  });
}

var studentResponse = new Bacon.Bus();
var gradingResult = studentResponse.flatMap(_fauxAjax);
var contextId = studentResponse.flatMap(_fauxAjax);

Given this input:

studentResponse.push(1);
studentResponse.push(2);
studentResponse.push(3);

Desired output:

{studentResponse:1, gradingResult:1, contextId:1 }
{studentResponse:2, gradingResult:2, contextId:2 }
{studentResponse:3, gradingResult:3, contextId:3 }
Community
  • 1
  • 1
U Avalos
  • 6,538
  • 7
  • 48
  • 81

1 Answers1

2

If you define the two latter ajax requests as independent streams, I don't see a practical solution for making sure the values are related.

So, to make absolutely sure that you get the gradingResult and contextId responses that were triggered by the same studentResponse I'd say you have to do something like this:

studentResponse.flatMap(function(response) {
  return Bacon.combineTemplate({
    studentResponse: response,
    gradingResult: _fauxAjax(response),
    contextId: _fauxAjax(response)
  })
}).log()
raimohanska
  • 3,265
  • 17
  • 28