RxJS and WebWorkers RxJS and WebWorkers angularjs angularjs

RxJS and WebWorkers


I assume your web worker is sending an observable back to your main thread via a message.

Messages are intended to be used both ways, you can't send objects that expose functionality.

The solution is to have your webworker post messages, and then have a main-thread service handle those messages and pipe them into a Subject, which it exposes to your application as an IObservable.

Keep on mind that web worker messaging doesn't support channels, so you'll need to apply your own discriminator if you use messages on multiple areas of your app.


The short answer is that Rx doesn't introduce concurrency unless you instruct it to via SubscribeOn, ObserveOn or some transform operator like Buffer.

So any code in the "Subscribe" part of the Rx operator will run in the same thread you called .Subscribe(onNext etc). However the actual callbacks onNext, onError and onComplete will run on whatever thread the observer uses, you don't control this (unless you wrote the operator).

To ensure you receive calls on the UI thread you should add a .ObserveOn(UIDispatcherThread). This will guarantee the thread you are called back on and make it testable.

Hope that helps.


As others noted, communication between calling code and webworkers is serialized and so you cant send something that has behavior (such an observable) over the wire.

I've written a little helper that uses Rxjs to help resolve this and other pains of developing with webworkers. Read about it here, github repo here