RxJS and WebWorkers

Quick question

If I have a WebWorker that has a function that returns the Observable<Any> back to the user interface code, if I then subscribe to the Observable, is it an observable start in the user interface thread or a WebWorker thread?

I ask this question because I am writing an Angular2 application with RxJS, and to improve performance I want some of the hardworking observers to run in WebWorkers, passing a stream of results to the UI thread

+5
source share
3 answers

I assume that your web coder sends the observable back to your main thread through a message.

Messages are intended for use in both directions; you cannot send objects that reveal functionality.

The solution is for your website message messages and then the main thread service to process these messages and associate them with the object that it provides your application as IObservable.

Keep in mind that web worker messaging does not support feeds, so you need to use your own discriminator if you use messages in several areas of your application.

+5
source

The short answer is that Rx does not introduce concurrency unless you instruct it through SubscribeOn, ObserveOn, or some kind of conversion operator like Buffer.

Thus, any code in the "Subscribe" section of the Rx operator will run in the same thread that you named. Subscribe (onNext, etc.). However, the actual onNext, onError, and onComplete callbacks will be executed on any thread that the observer uses, you have no control over this (unless you wrote a statement).

To ensure that calls are received in the user interface thread, you must add .ObserveOn (UIDispatcherThread). This ensures that the thread you are invoked on again and make it verifiable.

Hope this helps.

+2
source

As others have noted, the connection between the calling code and the web workers is serialized and therefore you cannot send something that has behavior (such observable) through the wire.

I wrote a little helper that uses Rxjs to help solve this and other problems that arise when working with webmasters. Read about it here , github repo here

0
source

Source: https://habr.com/ru/post/1241921/


All Articles