RxJava development requires 5-Observables Transformation

Source: Internet
Author: User

RxJava development requires 5-Observables Transformation

In the previous chapter, we explored universal RxJava filtering methods. We learned how to usefilter()Method to filter the values we don't need, how to usetake()Get the subset of the emission element and how to use itdistinct()Function to remove duplicates. We learned how to usetimeout(),sample(), Anddebounce()Time.

In this chapter, we will learn how to transform the observability sequence to create a sequence that better meets our needs.

* Map family

RxJava provides several ing functions:map(),flatMap(),concatMap(),flatMapIterable()AndswitchMap(). All these functions act on an observed sequence, transform the values it emits, and return them in a new form. Let's use the appropriate examples of "real world" to learn one by one.

Map

RxJavamapThe function receives a specifiedFuncThe object is then applied to each value transmitted by the Observable. Demonstrate how to apply a multiplication function to each sent value to create a new Observable to transmit the converted data.

Consider the list of installed applications. How can we display the same list, but all names are in lower case. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Authorization + uq/K/B/J0tS4xLPJ1eLR + aO6PC9wPg0KPHByZSBjbGFzcz0 = "brush: java;"> private void loadList(List apps) { mRecyclerView.setVisibility(View.VISIBLE); Observable.from(apps) .map(new Func1(){ @Override public Appinfo call(AppInfo appInfo){ String currentName = appInfo.getName(); String lowerCaseName = currentName.toLowerCase(); appInfo.setName(lowerCaseName); return appInfo; } }) .subscribe(new Observable() { @Override public void onCompleted() { mSwipeRefreshLayout.setRefreshing(false); } @Override public void onError(Throwable e) { Toast.makeText(getActivity(), "Something went wrong!", Toast.LENGTH_SHORT).show(); mSwipeRefreshLayout.setRefreshing(false); } @Override public void onNext(AppInfo appInfo) { mAddedApps.add(appInfo); mAdapter.addApplication(mAddedApps.size() - 1,appInfo); } });}

As you can see, create the Observable we launched as usual, and addmapCall, we can create a simple function to updateAppInfoObject and provide a new version with a lower-case name to the observer.

FlatMap

In a complex scenario, we have an Observable that transmits a data sequence, and the data itself can also emit Observable. RxJavaflatMap()The function provides a way to pave the sequence, merge the data transmitted by the Observables, and finally use the merged result as the final Observable.

When processing a large number of Observables, it is important to remember that any Observables has an error,flatMap()The function will trigger its ownonError()Function and discard the entire chain.

The important thing is about merging: it allows crossover. As shown, this meansflatMap()In the final Observable, the function cannot guarantee the exact sequence of the source Observables.

ConcatMap

RxJavaconcatMap()Function solvedflatMap()As shown in:

FlatMapIterable

As a member of * map family,flatMapInterable()AndflatMap()Very similar. The only difference is that it forms pairs of source data and then generates Iterable instead of the original data and the generated Observables.

SwitchMap

As shown in,switchMap()AndflatMap()Similar to this: when the original Observable emits a new data (Observable), it will unsubscribe and stop monitoring the Observable generated by the previous data, and start to monitor the current one.

Scan

RxJavascan()A function can be considered as a accumulator function.scan()The function applies a function to each data transmitted by the original Observable. It fills in the result of the function back to the observed sequence and waits for it to be used together with the next data transmitted.

As a general example, A accumulators are provided:

Observable.just(1,2,3,4,5)        .scan((sum,item) -> sum + item)        .subscribe(new Subscriber
  
   () {            @Override            public void onCompleted() {                Log.d("RXJAVA", "Sequence completed.");            }            @Override            public void onError(Throwable e) {                Log.e("RXJAVA", "Something went south!");            }            @Override            public void onNext(Integer item) {                Log.d("RXJAVA", "item is: " + item);            }        });
  

The result is:

RXJAVA: item is: 1RXJAVA: item is: 3RXJAVA: item is: 6RXJAVA: item is: 10RXJAVA: item is: 15RXJAVA: Sequence completed.

We can also create a new versionloadList()The function is used to compare the names of each installed application to create a list with an increasing name length.

private void loadList(List
  
    apps) {    mRecyclerView.setVisibility(View.VISIBLE);    Observable.from(apps)            .scan((appInfo,appInfo2) -> {                if(appInfo.getName().length > appInfo2.getName().length()){                    return appInfo;                } else {                    return appInfo2;                }            })            .distinct()            .subscribe(new Observable() {                @Override                public void onCompleted() {                    mSwipeRefreshLayout.setRefreshing(false);                }                @Override                public void onError(Throwable e) {                    Toast.makeText(getActivity(), "Something went wrong!", Toast.LENGTH_SHORT).show();                    mSwipeRefreshLayout.setRefreshing(false);                }                @Override                public void onNext(AppInfo appInfo) {                    mAddedApps.add(appInfo);                     mAdapter.addApplication(mAddedApps.size() - 1,appInfo);                }            });}
  

The result is as follows:

There isscan()Function variation, which uses the initial value as the first emission value. The features of the method are like:scan(R,Func2), As shown in the following example:

GroupBy

Starting with the first example, the list of installed applications is sorted in alphabetical order. However, what if we want to sort our apps by the latest update date? RxJava provides a useful function to follow the specified rules from the list:groupBy()To group elements. The example ingroupBy()How to group the emission values according to their shapes.

This function transforms the source Observable into a new Observable that transmits the Observables. Each of these new Observable transmits a set of specified data.

To create a list of installed applications in the grouploadList()A new element is introduced in the function:

Observable
  
   
    > groupedItems = Observable.from(apps)    .groupBy(new Func1(){        @Override        public String call(AppInfo appInfo){            SimpleDateFormat formatter = new SimpleDateFormat("MM/yyyy");            return formatter.format(new Date(appInfo.getLastUpdateTime()));        }    });
   
  

Now we have created a new Observable,groupedItems, Will launchGroupedObservable.GroupedObservableIs a special Observable, which is derived from the key of a group. In this example, the key isString, Which indicatesMonth/YearThe latest updated date formatted.

In this regard, we have created several launchAppInfoData Observable, used to fill our list. We want to keep the alphabetic order and group order. We will create a new Observable to connect all of them and subscribe to it as usual:

Observable.concat(groupedItems)    .subscribe(new Observable
  
   
    () {        @Override        public void onCompleted() {            mSwipeRefreshLayout.setRefreshing(false);        }        @Override        public void onError(Throwable e) {            Toast.makeText(getActivity(), "Something went wrong!", Toast.LENGTH_SHORT).show();            mSwipeRefreshLayout.setRefreshing(false);        }        @Override        public void onNext(AppInfo appInfo) {            mAddedApps.add(appInfo);             mAdapter.addApplication(mAddedApps.size() - 1,appInfo);        }    });
   
  

OurloadList()The function is complete and the result is:

Buffer

In RxJavabuffer()The function transforms the source Observable into a new Observable. This new Observable emits a set of list values each time rather than one by one.

Shown inbuffer()How to SetcountAs a parameter, you can specify how many data items are included in the emission list. Actually,buffer()There are several variants of a function. You can specify oneskipValue: After receiving the skip item data, the data will be filled in with the count item data. As shown in:

buffer()With onetimespanTo create an Observable that emits a list every timespan.

Window

RxJavawindow()Functions andbuffer()It is similar, but it is Observable rather than list when launching. Shownwindow()How to cache three data items and transmit them as a new Observable.

Each of these Observables emits a subset of the original Observable data.countSpecify the last oneonCompleted()End. Asbuffer()Same,window()There is alsoskipVariations, as shown in:

Cast

RxJavacast()Function is the last operator in this chapter. It ismap()Special version of the operator. It converts each data item in the source Observable to a new type and converts it to a differentClass.

Summary

In this chapter, we learned how to control and convert observability sequences in RxJava. With the knowledge we have learned, we can create, filter, and convert observed sequences of any type we want.

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.