RxJava combining two (or more) observable data sources

Source: Internet
Author: User
Tags emit

Keywords: merge Observable

Objective

In Rxjava, it is a common operation to handle multiple observables at the same time. The following is a simple analysis of the next few combinations of the operators of the class.

If you don't want to see the operator's introduction, you can skip to the actual combat section of the project.

Merge

In the asynchronous world often creates such scenes, we have multiple sources but want only one result: multi-input, single output. Rxjava's merge () method will help you merge two or more observables into the data they launch. The observable of combining two sequences in a final emission is given.

As you can see, the emitted data is cross-merged into a observable. Note If you synchronize the merged observable, they will be concatenated together and will not intersect.

Sample code

We created the observable and Observableapps data as well as the new Observablereversedapps inverse sequence table. Using Observable.merge (), we can create new observable--mergedobservable to emit all the data emitted from the source observables in a single observable sequence.

The results of the operation are as follows:

Attention:
The observable data type does not change after the merge operation conforms.

Zip

When dealing with multiple sources, we may have a scenario where we receive data from more than one observables, process them, and then combine 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. Shows how the zip () method handles the emitted "numbers" and "letters" and then merges them into a new data item:

Website introduction more details: http://reactivex.io/documentation/operators/zip.html

As you can see, the zip operator is not just merging the data like the merge operator, it's important that there is a qualitative change.

For the "real world" example, we'll use the list of installed apps and a new dynamic observable to make the example a bit more interesting.

Observable<Long> tictoc = Observable.interval(1, TimeUnit.SECONDS);

The TICTOC observable variable uses the interval () function to generate a long type of data per second: simple and efficient, as previously stated, we need a Func object. Because it needs to pass two parameters, it is FUNC2:

privateupdateTitle(AppInfoappInfo, Long time) {    " " + appInfo.getName());    return appInfo;}

The preceding loadlist () function becomes this:

As you can see, the zip () function has three parameters: two observables and one FUNC2.

The results are as follows:

Attention:
The observable data type can change after the zip operation conforms to and.

Join

The first two methods, the zip (), and the merge () methods function 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 the data emitted by two observables based on a time window.

To correctly understand the previous diagram, we explain the parameters required for join ():

    • The second observable is combined with a source observable.
    • FUNC1 parameter: In the specified time interval defined by the time window, the data emitted by the source observable and the data emitted from the second observable mate with each other observable returned.
    • FUNC1 parameter: In the specified time interval defined by the time window, the data emitted by the second observable and the data emitted from the source observable mate with each other to return observable.
    • FUNC2 parameter: Defines how the emitted data is combined with the newly emitted data item.

As an example of the exercises below, we can modify the Loadlist () function like this:

We have a new object appssequence, which is an observable sequence that launches app data every second from the list of apps we've installed. Tictoc This observable data emits only a new long integer per second. To merge them, we need to specify two FUNC1 variables:

appInfo -> Observable.timer(2, TimeUnit.SECONDS)time -> Observable.timer(0, TimeUnit.SECONDS)

Two time windows are described above. The following line describes how we can use FUNC2 to combine two of the emitted data.

this::updateTitle

The results are as follows:

It looks a bit messy, but note the name of the app and the time window we specify, we can see: Once the second data is emitted we will combine it with the source data, but we use the same source data for 2 seconds. This is the reason why the title repeats the number accumulation.

It is worth mentioning that, for the sake of simplicity, there is also a join () operator that acts on the string and then simply joins the emitted string into the final string.

Combinelatest

Rxjava's Combinelatest () function is somewhat like a special form of a zip () function. As we have learned, zip () acts on the recently unpacked two observables. 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, as shown in:

The Combinelatest () function accepts two to nine observable as arguments, if necessary, or a single observables list as a parameter.

To borrow the Loadlist () function from the previous example, we can modify it for the combinelatest () implementation of the Loadlist ():

We used two observables: one to launch one app per second from the list of apps we've installed, and the second to emit a long integer every 1.5 seconds. We combine them and execute the Updatetitle () function, and the results are as follows:

As you can see, because of the different time intervals, the AppInfo objects are sometimes repeated as we expected.

And,then and when

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. They merge the emitted datasets together under the joins package of Rxjava, using pattern and plan as mediations.

Our loadlist () function will be modified from this:

As usual, we have two launch sequences, Observableapp, launch our installed app list data, Tictoc emit a long integer per second. Now we connect the source observable and the second observable with and ().

JoinObservable.from(observableApp).and(tictoc);

Here we create a pattern object that we can use to create a plan object: "What do we do with two of Observables,then () that emit data?" ”

pattern.then(this::updateTitle);

Now we have a plan object and when plan happens we can decide what happens next.

.when(plan).toObservable()

At this point, we can subscribe to the new observable, as we always do.

Switch

One such complex scenario is that in a subscribe-unsubscribe sequence we can automatically unsubscribe from a 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

We have learned how to connect multiple observables and append the specified value to a sequence of launches. Rxjava's Startwith () is the counterpart of 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.

Summary

From the above analysis, we learned how to combine two or more observable to create a new observable sequence. We will be able to merge Observable,join observables, zip observables and combine them in several situations.

Say so much, or come to a practical scene.

Project actual needs

Download more than one picture at a time

Ideas

1. Create a picture URL list data stream using the from operator
2. Get a single URL and download

The code is as follows:

Note: This code does not implement the function of saving pictures, if necessary, refer to: http://blog.csdn.net/six_god_2/article/details/51363424

This does realize the function of downloading pictures, but in the OnNext method if we want to save the name of the image according to the URL address, this problem arises, OnNext method we can only get responsebody, how to solve it?

The key to solving the problem is to use the Func1 method in the Flatmap operator as long as the URL information is returned here, that is, responsebody and URL together.

By looking up the API, we finally found the zip operator for our merge observable. Why choose the zip operator instead of the merge operator? The beginning of the article has been explained.

The final code is as follows:

If the picture is not clear, the right mouse button can be viewed in the New tab page.

This is my way of realization, if you have a better, please leave a message to point out!

That's all, thank!

2016.09.02

Reference article: http://blog.csdn.net/bboyfeiyu/article/details/50512449

RxJava combining two (or more) observable data sources

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.