Search code examples
jquerypromisereactive-extensions-js

How to combine Rx.js subscription with Jquery Promise?


I use Rx.js and JqueryPromises I have run into a situation where i call a method to process an event published by Rx. This method however returns a promise.

eventStream.Subscribe(function(e) { methodThatReturnsPromise(e);});

The problem is that the processing of events is no longer deterministic. As methodThatReturnsPromise returns immediately as it defers processing.

My question :) Is there a way to "wait" on a promise? Is there any hooks for Rx to use promises i.e. chain the returned promise of a subscribe to the next returned promise of subscribe, so messages are still processed in order?


Solution

  • This code seems to do the trick for anyone else interested. I just need to chain the return deferreds.

    Fiddle here

    var seed = $.Deferred();
    seed.resolve();
    observable.aggregate(seed, function(chain, n){
        return chain.then(function(){
            console.log("Starting on Event " + n);
            return process(n);
        });
    }).subscribe();