preface

  • RxjavaBecause of itsChain call based on event flow, simple logic & easy to useThe characteristics of the deepAndroidDeveloper welcome.





Making screenshots

If you are not familiar with RxJava, check out Android: a clear and easy-to-understand introduction to RxJava

  • RxJavaThat’s why it’s so popularProvides rich & powerful operators that can fulfill almost all functional requirements
  • Today, I’m going to bring youRxjavaOf the create operatorCommon development scenarios: Merge data source requirements, and combined withRetrofitRxJavaImplementation, I hope you like it.
  1. This series of articles is based onRxjava 2.0
  2. In the coming days, I will continue to publish a series of articles on Rxjava 2.0 in Android, including principles, operators, application scenarios, back pressure, etc. If you are interested, please continue to follow Carson_Ho’s Android development notes!!





Schematic diagram


directory





Schematic diagram


1. Requirement scenario





Schematic diagram


2. Function Description

That is, fetch data from two sources at the same time -> merge data -> uniformly present to the client


3. Implementation

The Merge () & Zip () operators are used here, where:

  • Merge ()Example: To achieve relatively simple data acquisition from (network + local) & unified display
  • Zip ()Example: CombiningRetrofitRxJava, to achieve more complexMerge 2 network requests to get data to 2 servers & unified display

3.1 Use the Merge () operator

  • The specific implementation

For more information about the Merge () operator, see Android RxJava: Merge/Merge operators

String result = "Data source from ="; Observable<String> network = observable. just(" network "); Observable<String> file = observable. just(" local file "); /* * Merge events by merge() **/ Observable. Merge (network, file) .subscribe(new Observer<String>() { @Override public void onSubscribe(Disposable d) { } @Override public void OnNext (String value) {log. d(TAG, "data source has: "+ value); result += value + "+"; } @override public void onError(Throwable e) {log.d (TAG, "response to Error "); } @override public void onComplete() {log.d (TAG, "data completed "); Log.d(TAG, result ); }});Copy the code
  • The test results





Schematic diagram

  • Carson_Ho Github address = RxJava2

3.2 Use the Zip () operator

For more information about using the Zip () operator, see Android RxJava: Combine/merge operators

  • In this example, I will combine Retrofit with RxJava to implement:

    1. Fetching data from different data sources (2 servers), i.e. merging the sending of network requests
    2. Unified display of results
  • The implementation scheme uses Get method to send two network requests to Kingsoft POWERword API (translate English into Chinese, translate two times) & display the results of the two translations together.

Gson is used for data parsing





Kingsoft dictionary

  • Step-by-step instructions
    1. Add the dependent
    2. Create a class that receives data from the server
    3. Create an interface to describe network requests
    4. Create a Retrofit instance
    5. Create a network request interface instance and configure the network request parameters
    6. Sending network Requests
    7. Sending network Requests
    8. Process the returned data

This example focuses on thread control in RxJava. For more information about Retrofit, see the article: This is a very detailed tutorial on how to use Retrofit 2.0.

  • Steps to implement
Step 1: Add dependencies

A. Add Retrofit library dependencies in Gradle

build.gradle

Dependencies {/ / Android support Rxjava / / here it is important to note that the use of RxJava2 version the compile 'IO. Reactivex. RxJava2: Rxjava: 2.0.1' compile 'IO. Reactivex. Rxjava2: rxandroid: 2.0.1' / / Android support to Retrofit the compile 'com. Squareup. Retrofit2: Retrofit: 2.1.0' / / cohesion Retrofit & RxJava / / here it is important to note that the use of RxJava2 version the compile 'com. Jakewharton. Retrofit: retrofit2 RxJava2 - adapter: 1.0.0' / / support Gson parsing The compile 'com. Squareup. Retrofit2: converter - gson: 2.1.0'}Copy the code

B. Add the network permission androidmanifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
Copy the code
Step 2: Create the class that receives the data returned by the server
  • powerwordAPIThe data format is described as follows:
/ / http://fy.iciba.com/ajax.php / / URL examples http://fy.iciba.com/ajax.php?a=fy&f=auto&t=auto&w=hello%20world URL template / / parameter description: // a: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // f: fy // Text type: Ja for Japanese, zh for Chinese, EN for English, KO for Korean, DE for German, ES for Spanish, FR for French, auto // w for automaticCopy the code
  • The sample





API Format Description

  • According to kingsoft POWERword API data format, create a class to receive the data returned by the server:

To demonstrate that there are two network requests, set up the corresponding data classes for two receiving servers

<-- Translation1.java --> public class Translation1 { private int status; private content content; private static class content { private String from; private String to; private String vendor; private String out; private int errNo; } public String show() {return (" first translation =" + content.out); } } <-- Translation2.java --> public class Translation2 { private int status; private content content; private static class content { private String from; private String to; private String vendor; private String out; private int errNo; } public String show() {return (" 2nd 翻译=" + content.out); }}Copy the code
Step 3: Create an interface to describe network requests

Use the annotation + Observable<… > Interface Description Network request parameters

GetRequest_Interface.java

Public interface GetRequest_Interface {// network request 1 @get ("ajax.php? a=fy&f=auto&t=auto&w=hi%20world") Observable<Translation1> getCall(); @get ("ajax.php? a=fy&f=auto&t=auto&w=hi%20china") Observable<Translation2> getCall_2(); // Retrofit breaks the URL of the web request into two parts: // If the url in the interface is a complete URL, the url in the Retrofit object can be ignored. // Observable<... > interface // getCall() is the method to accept network request data}Copy the code
The next steps are inMainActivity.javaInternal implementation (see comments)

MainActivity.java

public class MainActivity extends AppCompatActivity { private static final String TAG = "Rxjava"; Observable1 observable1; observable1 observable1 observable1; Observable<Translation2> observable2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Step 1: Retrofit = new Retrofit.builder ().baseurl ("http://fy.iciba.com/") // Set the network request Url AddConverterFactory (GsonConverterFactory. The create ()) / / set using Gson parsing (remember to join rely on) AddCallAdapterFactory (RxJava2CallAdapterFactory. The create ()) / / support RxJava. The build (); GetRequest_Interface Request = retrofit.create(getrequest_interface-.class); // Step 2: Create an instance of the network request interface. // Step 3: Use Observable<... Observable1 = request.getCall().subscribe (schedulers.io ()); 1 observable2 = request.getCall_2(). // A new thread makes a network request 2 // that is, two network requests are sent asynchronously & simultaneously // Step 4: Observable1 (observable2, Observable2, new BiFunction<Translation1, Translation2, Translation2) String>() {// @override public String apply(Translation1 Translation1, Translation1) Translation2 translation2) throws Exception { return translation1.show() + " & " +translation2.show(); }}). ObserveOn (AndroidSchedulers mainThread ()) / / in the main thread to receive and process the data. The subscribe (new Consumer < String > () {/ / successful return data calls @override public void Accept (String combine_infro) throws Exception {// Combining the data result of two network requests log. d(TAG, "The received data is: " + combine_infro); }}, New Consumer<Throwable>() {@override public void Accept (Throwable) throws Exception { System.out.println(" login failed "); }}); }}Copy the code
  • The test results





Schematic diagram

  • Demo address Github address of Carson_Ho: RxJava_ Merge data source

4. To summarize

  • This article mainly explainsRxjavaReal development requirements scenario: merge data source requirements, and combineRetrofitRxJavaimplementation
  • Now I’m going to combineActual scenario application &RxjavaRelevant use frameworks (e.gRetrofit,Eventbus), continue toAndroidIn theRxjavaThe actual development requirements scenario for in-depth explanation, interested can continue to pay attention toCarson_Ho android Development Notes





Schematic diagram


Thumb up, please! Because your encouragement is the biggest power that I write!

Android Rxjava: create operator Android Rxjava: create operator Android Rxjava: create operator Android Rxjava: create operator Android Rxjava: create operator Android Rxjava: create operator Android Rxjava: create operator Android Rxjava: create operator Android Rxjava: Android RxJava network request polling Android RxJava network request nested callback Android RxJava network request nested callback Retrieve cached data from disk/memory caches


Welcome to attentionCarson_HoJane books!

Share the dry things about Android development from time to time, the pursuit of short, flat, fast, but there is no lack of depth.