RxJava--Concise asynchronous operation (ii)

Source: Internet
Author: User

In the last two examples, the issue and consumption of events are on the same thread. If only the above method is used, the implementation is only a synchronous observer pattern. The object of the observer pattern itself is the asynchronous mechanism, so asynchrony is essential for RxJava. To implement Asynchrony, you need to use another concept of RxJava: Scheduler . This article will introduce the use of scheduler:

3. Threading Control--scheduler (i)

By default, RxJava follows the thread-invariant principle of which thread is called on which thread produces the event, and in which thread the event is subscribe() consumed. If you need to switch threads, you need to use the Scheduler (scheduler).

1) Scheduler API (i)

In RxJava, the Scheduler -Scheduler, the equivalent of a thread controller, RxJava it to specify what thread each piece of code should run on. RxJava has several built-in Scheduler , which are already suitable for most usage scenarios:

    • schedulers.immediate () : Runs directly on the current thread, equivalent to not specifying a thread. This is the default   Scheduler .

    • schedulers.newthread () : Always enable new threads and perform operations on new threads.

    • schedulers.io () :   used by I/O operations (read and write files, read-write databases, network information interactions, and so on) Scheduler . behavior patterns and   newthread ()   Almost, the difference is   io ()   Internal implementation is the use of an unlimited number of thread pools, you can reuse idle threads, So in most cases   io ()   more efficient than   Newthread ()  . Do not put the calculation work in   io ()  , you can avoid creating unnecessary threads.

    • schedulers.computation () : Calculates the   used; Scheduler . This calculation refers to CPU-intensive computations, i.e., operations that do not restrict performance by operations such as I/O, such as the calculation of a sample. This   Scheduler   uses a fixed thread pool that is the size of the CPU core. Do not place I/O operations in   computation ()  , otherwise the wait time for I/O operations wastes the CPU.

    • Additionally, Android has a dedicated   androidschedulers.mainthread () , which specifies that the operation will run on the Android main thread.

With these Scheduler , you can use subscribeOn() and observeOn() two methods to control the threads. * subscribeOn() : Specifies the thread subscribe() that occurs, that is, the Observable.OnSubscribe thread that is active. Or an event-generated thread. * observeOn() : Specifies the Subscriber thread that is running. Or a thread called event consumption.

With these Scheduler , you can use subscribeOn() and observeOn() two methods to control the threads. * subscribeOn() : Specifies the thread subscribe() that occurs, that is, the Observable.OnSubscribe thread that is active. Or an event-generated thread. * observeOn() : Specifies the Subscriber thread that is running. Or a thread called event consumption.

In the above code, because subscribeOn(Schedulers.io()) of the specified, the content of the created event will be 1到11  emitted on the IO thread, and as a result of observeOn(AndroidScheculers.mainThread() the specified, so the subscriber number of printing will occur in the main thread. In fact, this subscribe() is very common in the previous writing of two sentences subscribeOn(Scheduler.io()) observeOn(AndroidSchedulers.mainThread()) , and it applies to most of the "background thread fetching data, main thread display" program policy.

It will then appear at the end of the TextView main thread.

Picture is the same as the truth

4. Transformations

RxJava provides support for transforming the sequence of events, one of its core functions, and the biggest reason most people say "RxJava is so Good". A transformation is the process of processing an object or an entire sequence in an event sequence into different events or sequences of events. The concept is always vague and difficult to read, so look at the API.

There is a class called Func1 . It Action1 is very similar to, and is also an interface for RxJava, to wrap a method that contains a parameter. Func1The Action difference is that the Func1 wrapper is a method that has a return value. In addition, ActionX as with, FuncX there are several methods for the number of different parameters. FuncXand ActionX the difference in FuncX packaging is that there is a way to return the value.

As you can see, the map() method returns the object in the argument after it has String been converted to an Bitmap object, and after the method is passed map() , the argument type of the event String Bitmap is converted. This direct transformation of objects and returns is the most common and easiest to understand transformations. But RxJava's transformation is much more than that, and it can be used not only for event objects but also for the entire event queue, which makes RxJava very flexible. I cite a few common transformations:

map(): The direct transformation of the event object, as described in the specific function above. It is the most commonly used transformation of RxJava \

● flatMap(): This is a very useful but very difficult to understand transformation, so I decided to spend more space to introduce it.

Let's start with the assumption that there is a data structure, "students," that now needs to print out a group of students ' names. The implementation method is simple:

Public String changstudent () {

student[] Students = ...;
subscriber<string> subscriber =NewSubscriber<string> () {
@Override
Public voidOnNext (String name) {
Log.D(Tag, name);
}
...
};
Observable.from (students)
. Map (NewFunc1<student, string> () {
@Override
PublicString Call (Student Student) {
returnStudent.getname ();
}
})
. Subscribe (subscriber);
}

Very simple. So, what if you want to print out the names of all the courses that each student needs to fix? (The difference between the requirements is that each student has only one name, but there are multiple courses.) This can be achieved first:

   student[] Students = ...;
subscriber<student> subscriber = new subscriber<student> () {
@Override
public void OnNext (Student Student) {
list<course> courses = student.getcourses ();
for (int i = 0; i < courses.size (); i++) {
Course Course = Courses.get (i);
LOG.D (tag, course.getname ());
}
}
...
};
Observable.from (students)
. Subscribe (subscriber);

is still very simple. So what if I don't want to use a for Subscriber loop in, but want to Subscriber pass in a single Course object directly (which is important for code reuse)? It's map() obviously not working, because map() it's a one-way conversion, and my current requirement is a one-to-many conversion. So how can you convert a Student into multiple Course?

This time, it needs to be used flatMap() :

student[] Students = ...;
subscriber<course> subscriber = new subscriber<course> () {
@Override
public void OnNext (Course Course) {
LOG.D (tag, course.getname ());
}
...
};
Observable.from (students)
. FLATMAP (New func1<student, observable<course>> () {
@Override
Public observable<course> Call (Student Student) {
Return Observable.from (Student.getcourses ());
}
})
. Subscribe (subscriber);

Follow the public number for more information:

RxJava--Concise asynchronous operation (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.