Quick question
If I have a WebWorker
that has a function that returns an Observable<Any>
back to the UI code, if I then subscribe to the Observable, is the observable running on the UI thread or the WebWorker
thread?
I ask this question because I am writing an Angular2 app with RxJS, and to improve performance I want some of the hard-working Observables to run within WebWorkers, passing a stream of results over to the UI thread
Web workers lets you run CPU-intensive computations in a background thread, freeing the main thread to update the user interface.
RxJS also has a fromWorker that takes the URL to your Web Worker: github.com/Reactive-Extensions/RxJS-DOM/blob/master/doc/…
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With