An appetizer

Without further further, let’s see how to send a Get request.

RxHttp.get("http://...")  // The first step is to determine the request type. You can select postForm, postJson, and other methods
    .asString()           // The second step is to determine the return type. String is mandatory here
    .subscribe(s -> {     // The third step is to subscribe to the observer. The second step is to return an Observable
        // The request succeeded
    }, throwable -> {                                  
        // The request failed
    });                                                
Copy the code

Ok, the countdown is over!! At this point, you’ve learned the essence of RxHttp.

Yes, no doubt, it’s as simple as that. With RxHttp, any request, any return data type, follows these three steps, which we call the request trilogy:

Say important things three times

Any request, any returned data type, follows the request trilogy

Any request, any returned data type, follows the request trilogy

Any request, any returned data type, follows the request trilogy

Gradle rely on

  • OkHttp 3.14.x or later, the minimum requirement is API 21. If you want to be compatible with API 21 or below, please rely on OkHttp 3.12.x, which requires API 9

  • The asXxx method is implemented internally through RxJava, and RxHttp version 2.2.0, RxJava has been excluded from the internal, if you need to use RxJava, please rely on RxJava and tell RxHttp to rely on the RxJava version

1, will be selected

Add the JitPack to your project’s build.gradle file as follows:

allprojects {
    repositories {
        maven { url "https://jitpack.io"}}}Copy the code

Note: RxHttp has been fully migrated from JCenter to JITPack since version 2.6.0

// Must be used when kapt relies on rxhttp-compiler
apply plugin: 'kotlin-kapt'

android {
    // Must, Java 8 or higher
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation 'com. Making. Liujingxing. RXHTTP: RXHTTP: server'
    implementation 'com. Squareup. Okhttp3: okhttp: 4.9.0' // From RXHTTP v2.2.2, you need to manually rely on okhttp
    kapt 'com. Making. Liujingxing. RXHTTP: RXHTTP - compiler: server' // Generate RxHttp class, pure Java project, please use annotationProcessor instead of kapt
 }
Copy the code

2, optional

android {
    defaultConfig {
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [
                    rxhttp_package: 'rxhttp'.// Optional, specify the RxHttp class package name
                    // Pass the version of RxJava that you depend on. You can pass rxJavA2, rxJavA3, but you must if you depend on RxJava
                    rxhttp_rxjava: 'rxjava3'

                ]
            }
        }
    }
}
dependencies {
    implementation 'com. Making. Liujingxing. Rxlife: rxlife - coroutine: 2.1.0' // Manage the coroutine life cycle, page destruction, close requests
    
    //rxjava2 (rxjava2 /Rxjava3)
    implementation 'the IO. Reactivex. Rxjava2: rxjava: 2.2.8'
    implementation 'the IO. Reactivex. Rxjava2: rxandroid: 2.1.1'
    implementation 'com. Making. Liujingxing. Rxlife: rxlife - rxjava2:2.1.0' // Manage the RxJava2 lifecycle, page destruction, close requests

    //rxjava3
    implementation 'the IO. Reactivex. Rxjava3: rxjava: 3.0.6'
    implementation 'the IO. Reactivex. Rxjava3: rxandroid: 3.0.0'
    implementation 'com. Making. Liujingxing. Rxlife: rxlife - rxjava3:2.1.0' // Manage the RxJava3 lifecycle, page destruction, close requests

    RxHttp has GsonConverter built in by default
    implementation 'com. Making. Liujingxing. RXHTTP: converter - fastjson: server'
    implementation 'com. Making. Liujingxing. RXHTTP: converter - Jackson: server'
    implementation 'com. Making. Liujingxing. RXHTTP: converter - moshi: server'
    implementation 'com. Making. Liujingxing. RXHTTP: converter - protobuf: server'
    implementation 'com. Making. Liujingxing. RXHTTP: converter - simplexml: server'
}
Copy the code

Finally, rebuild (which is required), and the RxHttp class is automatically generated

Trilogy commentary

I’m sure a lot of people have questions by now

  • What if I want to send a Post or something?
  • What about monitoring file uploads, downloads, and progress?
  • What if I want a custom data type?

How does this happen in a trilogy? Don’t worry. I’ll tell you all about it

The first step is to determine the request mode

In the example above, we call rxhttp.get (“http://…”) ), where the GET operator represents the GET request. From this, we can guess that to send a Post request, we simply need to call the Post operator. But we were only half right. Why? In Post request, we are divided into two types, one is the form of Post, the other is the FORM of Json string Post. To do this, RxHttp provides two operators for sending Post requests, postForm and postJosn, so we can send a Post request like this

RxHttp.postForm("http://...")  // Send a form Post request
    .asString()                // Mandatory String
    .subscribe(s -> {          // Subscribe to observer,
        // The request succeeded
    }, throwable -> {                                  
        // The request failed
    });  
    
RxHttp.postJson("http://...")  // Send a Post request in the form of a Json string
    .asString()                // Mandatory String
    .subscribe(s -> {          // Subscribe to observer,
        // The request succeeded
    }, throwable -> {                                  
        // The request failed
    });    
Copy the code

If you want to send Delete, Put, and other requests, the same is true:

RxHttp.deleteForm("http://...")
RxHttp.deleteJson("http://...")
RxHttp.putForm("http://...")
RxHttp.putJson("http://...")
// Other requests are as above
Copy the code

And finally, let’s look at,RxHttpWhich request methods are provided, as follows:Among themget,postForm,postJsonThat’s already been done, and the rest of it is the same, so I won’t talk about it here.

The request mode is determined, how to add parameters or profile picture information? so easy!!! , just call add and addHeader, as follows:

RxHttp.postForm("http://...")  // Send a form Post request
    .add("key"."value")        // Add the request parameter. This method can be called multiple times
    .addHeader("headerKey"."headerValue")  // Add the request header parameter. This method can be called multiple times
    .asString()                // Mandatory String
    .subscribe(s -> {          // Subscribe to observer,
        // The request succeeded
    }, throwable -> {                                  
        // The request failed
    }); 
Copy the code

The second step is to determine the return data type

RxHttp provides a series of asXXX operators, as follows:

Among them, asBoolean, asInteger, asLong, asString, etc., are the boxing types that return the basic type. I’m going to talk too much about this. Let’s focus on that hereasClass,asList,asDownloadThese three operators.

asClass

For example, if we want to get a Student object, we can use the asClass operator, as follows:

RxHttp.get("http://...")       // Send a Get request
    .asClass(Student.class)   // Specify to return data of type User
    .subscribe(student -> {    // Subscribe to observer,
        // The request succeeded, where student is the student object
    }, throwable -> {                                  
        // The request failed
    });  
Copy the code

asList

However, what if we wanted a list of Student objects? Using asObject is obviously not an option. In this case, use the asList operator, as follows:

RxHttp.get("http://...")        // Send a Get request
    .asList(Student.class)      // Specify to return data of type User
    .subscribe(students -> {    // Subscribe to observer,
        // The request succeeded, where students is the List
      
        object
      
    }, throwable -> {                                  
        // The request failed
    });  
Copy the code

Note: The asXXX operator internally specifies that the request is executed on the schedulers.io () thread by default

asDownload

When we need to download a file, we use this operator as follows:

 RxHttp.get("http://...")        / / Get request
     .asDownload("... /rxhttp.apk")  // Use the asDownload operator and pass in the path to the storage
     .subscribe(s -> {                                       
         // Download successful callback, s is the file storage path
     }, throwable -> {                             
         // Download failed callback
     });                                                     
Copy the code

For more file manipulation, check out Android’s most elegant implementation of file upload, download, and progress monitor

Step 3: Subscribe to observers

In the previous step, you may have noticed that using the asXXX operator returns an Observable. What is this object? It’s actually an Observable inside RxJava.

This tells you that when we call the asXXX operator and get the Observable, RxHttp has done its job and the rest is left to RxJava. Taking an Observable and using RxJava’s powerful operators, we can do a lot of things. For example, we want to call back the observer on the main thread, as follows:

RxHttp.get("http://...")        // Send a Get request
    .asList(Student.class)      // Specify to return data of type User
    .observeOn(AndroidSchedulers.mainThread())  // The main thread calls back to the observer
    .subscribe(students -> {    // Subscribe to observer,
        // The request succeeded, where students is the List
      
        object
      
    }, throwable -> {                                  
        // The request failed
    });  
Copy the code

Note: The request is executed on the Schedulers. IO () thread by default. If the observer thread is not specified, the request is called back on the requested thread by default

summary

All right, that’s the end of the request trilogy. At this point, you have mastered 70% of the functionality of RxHttp, and you have mastered the essence of RxHttp —- Request trilogy, in any request, you can do the same. The purpose of this article is to provide a simple introduction to the tutorial, see more

RxHttp is an impressive Http request framework

RxHttp, a more elegant coroutine experience than Retrofit

RxHttp is perfect for Android 10/11 upload/download/progress monitoring

RxHttp Optimal solution for network Http cache

In the process of using, such as what problems encountered, the environment plus group exchange RxHttp&RxLife exchange group: 378530627