Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS and WebWorkers

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

like image 982
Dean Chalk Avatar asked Jan 31 '16 10:01

Dean Chalk


People also ask

What are web workers in angular?

Web workers lets you run CPU-intensive computations in a background thread, freeing the main thread to update the user interface.

Does RxJS use web workers?

RxJS also has a fromWorker that takes the URL to your Web Worker: github.com/Reactive-Extensions/RxJS-DOM/blob/master/doc/…


3 Answers

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.

like image 111
Richard Szalay Avatar answered Oct 02 '22 18:10

Richard Szalay


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.

like image 25
user630190 Avatar answered Oct 02 '22 18:10

user630190


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

like image 30
asi Avatar answered Oct 02 '22 20:10

asi