An in-depth explanation of RxJava_07 [Multi-threading & auxiliary operations (End)]
黄舟
Release: 2017-03-04 10:00:26
Original
1640 people have browsed it
In Android APP, we often need to access the network to obtain data. Requesting network data needs to be operated in a sub-thread. This requirement is broken down as follows:
Network requests are placed in the observer (child thread).
Network request result processing is placed in the observer (main thread).
Subscription (when the network request is completed, it is convenient for the observer to notify the observer)
In order to better realize the above requirements, we Need to know how to use a specific thread to handle the subject and observer. The following article will introduce thread-related operations in RxJava.
1.ObserveOn
Specify the scheduler on which an observer observes this Observable.
In RxJava, to specify the scheduler on which the Observable should call the observer's onNext, onCompleted, and onError methods, you need to use the observeOn operator and pass it a suitable Scheduler.
The above code is mainly called in the main thread, so it is printed by the observer is the main thread, and the observeOn function is used, causing the observer to jump to the RxIoScheduler-2 thread to run.
I don’t know if you have noticed that Schedulers.io() in the above code specifies the type of child thread. In addition, there are many thread types. As shown in the following table:
Scheduler type
Effect
Schedulers.computation( )
Used for computing tasks, such as event loops or callback processing, not for IO operations (please use Schedulers.io() for IO operations); the default number of threads is equal to the number of processors
Schedulers.from(executor)
Use the specified Executor as the scheduler
##Schedulers.immediate()
In The current thread starts executing the task immediately
Schedulers.io()
is used for IO-intensive tasks, such as asynchronous blocking IO operations. The thread pool of this scheduler will be based on Needs to grow; for ordinary computing tasks, please use Schedulers.computation(); Schedulers.io() defaults to a CachedThreadScheduler, much like a new thread scheduler with a thread cache
Schedulers.newThread()
Create a new thread for each task
Schedulers.trampoline()
When other queued tasks are completed, Start executing in the queue of the current thread
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn