RxJava Method Memo

Source: Internet
Author: User
Tags emit

RxJava method

Filter related

Rxjava provides the filter () method to filter unwanted values in our observation sequence.

When we don't need the whole sequence, we just want to take a few elements at the beginning or the end, we can use take () or takelast ()

An observable sequence is repeated in the case of an error or is designed to repeat the launch. The distinct () and distinctuntilchanged () functions allow us to handle this repetition problem conveniently. (It will record as well as the emitted values to filter, so please note the memory)

The first () method and The last () method are easy to figure out. They emit only the first element or the last element from the observable. Both of these can be passed Func1 as arguments: a predicate that can determine the first or last of our interest:

The Skip () and Skiplast () functions correspond to take () and Takelast (). They use integer n as a parameter, essentially they do not let observable emit the first n or the last n values. We can use it if we know that a sequence begins or ends with a "controllable" element that does not have too much to use.

The ElementAt () function emits only the nth element from a sequence and can use Elementatordefault () if it is not feared to exist.

A temperature sensor that emits the current indoor temperature every second. To tell the truth, we don't think the temperature will change so fast, we can use a small launch interval. After adding a sample () to the observable, we will create a new observable sequence that will emit the most recent value from observable at a specified time interval:

Assuming we are working in a timely environment, our temperature sensors emit a temperature value every second. We want it to emit at least one every two seconds, and we can use the timeout () function to listen to the source observable sequence, which is to emit an error if we don't get a value within the time interval we set. We can assume that timeout () is a time-limited copy of a observable. If the observable does not emit a value within the specified time interval, it will trigger the onerror () function when it listens to the original observable.

The Debounce () function filters out data that is too fast to be emitted by observable, and if it is not fired at a specified time interval, it will launch the last one.

Just like the sample () and timeout () functions, debounce () uses the Timeunit object to specify the time interval.

Transform-related

Rxjava provides several mapping functions: Map (), FlatMap (), Concatmap (), flatmapiterable (), and Switchmap (). All of these functions are used for an observable sequence and then transform the values it emits, And finally return them in a new form.

In a complex scenario, we have a observable: it emits a sequence of data that can emit observable itself. The Flatmap () function of Rxjava provides a way to flatten the sequence, then merge the data emitted by these observables, and finally take the merged result as the final observable. When we are dealing with a potentially large number of observables, it is important to remember that any observables error occurs, and FLATMAP () will trigger its own onerror () function and discard the entire chain.

It is important to note that the merge section: it allows the intersection, so Flatmap () cannot guarantee the exact sequence of observables in the resulting observable.

The Concatmap () function solves the cross problem of Flatmap () and provides a flattening function that allows the values of the emission to be contiguous, rather than merging them, as shown in the following:

Witchmap () and Flatmap () are like, except for one thing: whenever the source Observable launches a new data item (Observable), it cancels the subscription and stops monitoring the Observable generated by the previous data item, and starts to monitor the current emitted

The scan () function can be seen as a cumulative function. The scan () function applies a function to each item of data emitted by the original observable, calculates the result value of the function, and fills the value back into the observable sequence, waiting to be used with the next emitted data.

GroupBy () transforms the source observable into a new observable that emits observables. Each of these new observable launches a set of specified data.

Buffer () transforms the source observable into a new observable, the new observable launches a set of list values each time instead of one

The window () function is similar to buffer (), but it emits a observable instead of a list, the number is specified by count, and the final firing of a oncompleted () ends. As in buffer (), window () also has a skip variant

The cast () function is a special version of the map () operator. It converts every item in the source observable to a new type, turning it into a different class.

Combination Observables

Merge () We have multiple sources but just want to have one result: multiple inputs, single output. Rxjava's merge () method will help you merge two or more observables into the data items they launch. The errors thrown by each observable will break the merge. If you need to avoid this situation, Rxjava provides mergedelayerror (), which can continue to emit data from a observable, that is, one of them throws an error. When all observables are complete, mergedelayerror () will emit onerror ()

Zip () handles multiple data sources when it comes to receiving data from more than one observables, processing them, and then merging them into a new observable sequence to use. Rxjava has a special method to complete: Zip () merges two or more observables emitted data items, transforms them according to the specified function func*, and emits a new value.

The zip () and merge () methods preceding the Join () Act in the context of the emitted data, and there are some scenarios in which we need to consider time before deciding how to manipulate the values. The join () function of Rxjava combines two observables emitted data based on a time window

Combinelatest () is a bit like a special form of a zip () function. Zip () acts on two observables that have not been packaged recently. Instead, combinelatest () acts on the recently launched data item: If Observable1 launches A and Observable2 launches B and c,combinelatest (), the AB and AC will be processed in groups.

In the future there are still some scenarios that the ZIP () cannot meet. such as complex architectures, or just for personal hobbies, you can use the And/then/when solution

Switch has such a complex scenario that in a subscribe-unsubscribe sequence we can automatically unsubscribe from an observable to subscribe to a new observable.

Rxjava switch (), as defined, converts a observable that emits multiple observables into another separate observable, which emits data items that observables recently launched.

A source Observable,switch () that emits multiple observables sequences is given a subscription to the source observable and then starts transmitting the same data emitted by the first observable emitted. When the source observable launches a new observable, switch () immediately cancels the observable of the previous transmit data (thus interrupting the stream from which it was emitted) and then subscribes to a new observable and starts transmitting its data.

Startwith () is the corresponding part of the concat (). Just as concat () appends data to the observable of the emitted data, startwith () emits a data sequence first by passing a parameter before observable starts transmitting their data.

Calling thread

Strictmode helps us detect sensitive activity, such as when we inadvertently perform disk access or network calls on the main thread. As you know, it is not advisable to perform heavy or long tasks on the main thread. Because the main thread of the Android app is the UI thread, it is used to handle UI-related actions: This is the only way to get a smoother animation experience and responsive app.

In order to activate Strictmode in our app, we only need to add a few lines of code in the mainactivity, i.e. the OnCreate () method

 @Overridepublic void OnCreate () {super.oncreate  ()  if (Buildconfig) {strictmode.setthreadpolicy  (New Strictmode  () .detectall  () .penaltylog  () .build  ())  Strictmode.setvmpolicy  (New Strictmode  () .detectall  () .penaltylog  () .build  ())  } }

We don't want it to always be active, so we only use it when debug builds. This configuration will report every violation of the main thread usage, and these practices may be related to memory leaks: activities, broadcastreceivers, SQLite, and so on. +

Penaltylog () is selected, and Strictmode will print a message in Logcat when the violation occurs.

Blocking I/O causes the app to wait for the result to return (blocking the end) for the next step. Performing a blocking operation on the UI thread will force the UI to get stuck, causing a bad user experience directly.

After we activated Strictmode, we began to receive bad information about our app's error operation disk I/O.

D/strictmode Strictmode Policy violation; ~duration=998 ms:android.os.strictmode$strictmodediskreadviolation:policy=31 violation=2At Android. OS. Strictmode$AndroidBlockGuardPolicy. Onreadfromdisk(Strictmode. Java:1135) at Libcore. IO. Blockguardos. Open(Blockguardos. Java:106) at Libcore. IO. Iobridge. Open(Iobridge. Java:393) at Java. IO. FileOutputStream.<init> (FileOutputStream. Java: the) at Android. App. Contextimpl. Openfileoutput(Contextimpl. Java:918) at Android. Content. Contextwrapper. Openfileoutput(Contextwrapper. Java:185) atcom. Packtpub. Apps. Rxjava_essentials. Utils. Storebitmap(Utils. Java: -)

The previous message tells us that the Utils.storebitmap () function takes 998ms: Unnecessary work on the UI thread for nearly 1 seconds, and unnecessary dullness on the app for nearly 1 seconds. This is because we access the disk in a blocking manner. Our Storebitmap () function contains:

[Code] FileOutputStream fOut = context.openfileoutput (filename, context.mode_private);

It directly accesses the solid-state storage of the smartphone and then it slows down. How do we improve the speed of access? The Storebitmap () function saves the icon for the installed app. His return value type is void, so we have no reason to wait until it is done before performing the next operation. We can start it and let it execute on different threads. In recent years, there have been many changes in the thread management of Android, causing the app to behave strangely. We can use Asynctask, but we want to avoid falling into the onpre in the previous chapters ... onpost...doinbackground hell. Below we will change the way of using Rxjava. Hooray for the Scheduler!

      *

Schedulers.io () This scheduler is used for I/O operations. It is based on the need to grow or shrink from the adaptive thread pool. We will use it to fix the strictmode violation practices we saw earlier. Because it is dedicated to I/O operations, it is not the default method for Rxjava, and it is up to the developer to use it correctly.

It is important to note that the thread pool is unrestricted and that a large number of I/O scheduling operations will create many threads and consume memory. As always, we need to find an effective balance between performance and simplicity.

Schedulers.computation () This is the default scheduler for computing work, which is not related to I/O operations. It is also the default scheduler for many Rxjava methods: Buffer (), debounce (), delay (), interval (), sample (), Skip ().

Schedulers.immediate ()

This scheduler allows you to perform the work you specify immediately on the current thread. It is the default scheduler for timeout (), TimeInterval (), and Timestamp () methods.

Schedulers.newthread ()

The scheduler, as it looks, starts a new thread for the specified task.

Schedulers.trampoline ()

When we want to perform a task on the current thread, not immediately, we can use. Trampoline () to queue it. This scheduler will process its queue and sequentially run each task in the queue. It is the default scheduler for the repeat () and retry () methods.

Non-blocking I/O operations

Now that we know how to dispatch a task on a specified I/O Scheduler, we can modify the Storebitmap () function and check again for Strictmode's non-compliance practices. For this example, we can rearrange the code in the new Blockingstorebitmap () function.

FileOutputStream FOut =NULL;Try{fOut = context.openfileoutput (filename, context.mode_private); Bitmap.compress (Bitmap.CompressFormat.PNG, -, FOut);        Fout.flush ();    Fout.close (); }Catch(ExceptionE) {Throw NewRuntimeException (e); }finally{Try{if(FOut! =NULL) {fout.close (); }        }Catch(IOException e) {Throw NewRuntimeException (e); }    } }

Now we can use Schedulers.io () to create a non-blocking version:

    Schedulers.io().createWorker().schedule(() -> {        blockingStoreBitmap(context, bitmap, filename);    }); }

Every time we call Storebitmap (), the Rxjava process creates all of it needs to execute our task from a specific I/O thread in the I/O pool. All of the actions to be performed are avoided on the UI thread and our app is 1 seconds faster than before: there is no strictmode on Logcat.

Subscribeon and Observeon

The Subscribeon () method is used for each observable object. The Subscribeon () method uses scheduler as a parameter and executes observable calls on this scheduler

The Observeon () method will return the result on the specified scheduler

Summarize

Rxjava is a world that is constantly developing and expanding. There are many ways we haven't explored yet. There are some ways not even, through Rxjava, you can create your own operators and grow them farther. +

Android is a fun place, but it also has limitations. As an Android developer, you can overcome many of them with Rxjava and rxandroid. We use Androidscheduler to simply mention the next rxandroid, except in the last chapter, you know the viewobservable. Rxandroid gives you a lot: for example, widgetobservable,lifecycleobservable. It is up to you to take the longer-term task forward.

Keep in mind that observable sequences are like a river: they are flowing. You can "filter" a river, you can "convert" (transform) a river, you can merge the Two rivers (combine) into one, and then still flow as before. Finally, it becomes the river you want.

Reference: http://www.aichengxu.com/view/2473291

RxJava Method Memo

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.