简体   繁体   中英

How to execute observable in parallel threads

I have Observable called messages which contains several messages.I want to process these messages at the same time.How can i do this using rxJava??

messages.(code to execute observable items parallel).subscribe(msg->process(msg))

(If the observable contains five different messages then I need to process these five messages in five seperate threads)

If you want to stay in the Observable world, you can flatMap each element with subscribeOn and computation you want in parallel:

Observable.range(1, 10)
.flatMap(v -> 
    Observable.fromCallable(() -> compute(v))
    .subscribeOn(Schedulers.computation)
)
.subscribe(e -> { }, Throwable::printStackTrace);

Run single thread that "observe" your messages, and dispatch every message that it contains to new message handling task (eg simple Runnable ) that is submitted to some sort of workers thread pool .

Here you will find simple how-to: https://docs.oracle.com/javase/tutorial/essential/concurrency/executors.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM