preface

Today’s topic is The Web Request Framework, and today’s two protagonists are Retrofit and RXJava. This is the network request and data processing framework THAT I use in my current work project. I have also observed that many students in the group have been exposed to these two frameworks. I would like to share my insights and experience on the use of these two frameworks. I hope to arouse discussion on the inadequacies and shortcomings. Slap in the face!


Every time I approach a new subject, I have three things in mind:

  1. What is it?

  2. Why do you use it?

  3. How do I use it?

Through these three points, connect the dots to a line, and gradually you will get familiar with it, and finally you can integrate it into your knowledge base.


What is it?

retrofit

It is another square product that is popular for its easy interface configuration, powerful extension support, and elegant code structure. Retrofit is an encapsulation of a RESTful style HTTP Web request framework. Note that I’m not talking about the Web request framework here, mainly because the web request work is not done by Retrofit. OKHttp was built into retrofit2.0, with the former focusing on encapsulation of interfaces and the latter on efficient network requests. The OKHttp is a great engine, and the Retrofit is the perfect car shell and parts that not only make the best of the engine, but also make it easy for us to change the car into something we love.

rxjava

It is a popular function library in Android development. It focuses on responsive programming, where asynchronous events organize code in sequences. Make your ideas work in clear code. The key point here is reactive programming, and I’m going to click here, if you’re interested in learning about it, it’ll make it easier for you to understand RXJava.


Why do you use it?

I will first show you a piece of code that I wrote when I first started working in 2014. In the picture, I define a login request method, which requires passing in request parameters and request response listening. The request framework uses Volley. Here I will briefly introduce some volley, which is a network communication framework launched by Google in 2013. It can carry out HTTP communication very simply like AsyncHttpClient, and load images on the network as easily as Universal image-loader. However, Volley also has disadvantages, because volley is designed to be very suitable for network operations with small amount of data but frequent communication. Therefore, volley will perform badly in network operations with large amount of data, such as downloading/uploading files.

This is an external call to the request method. The first is an external call to the login request method, followed by an instantiation of a network request listener, where the logic is to parse json data and do logon-related logic, as well as handle exceptions that may arise from the login request

This is the parsing of the returned data.

Some of the drawbacks can be seen in the code above:

1. For example, I don’t want to do the tedious json parsing (I won’t discuss fastjson for now), and I want the data to be directly converted to bean objects

2. Error handling code is written all over the place and I want to have a unified management

3. We have to do a lot of fault tolerance to prevent the server from returning bad data to us.

In addition to the three points mentioned above, I also encountered some problems in the later work. For example, I was really bothered when I was doing file uploading, because Volley was not suitable for file uploading and wrote a lot of code related to uploading. For example, when multiple requests need to form a chain request, the code is so tedious that I don’t want to read the rest. So the later maintenance work to do a lot, the basic is their own digging their own step. And it’s a recognized fact that OKHttp is still a lot better than Volley.

While I was agonizing over the hole I had dug, retrofit and RXJava, two amazing frameworks that were slowly gaining popularity in China, and when I found out what they could do to solve many of my practical problems, I thought to myself: What the hell? Can it do that? . That’s why I use Retrofit and RXJava.


How do I use it?

Once we understand what it is and have convinced ourselves to use it, we need to see how it works and which position is best.

Let me show you a few basic classes that I need for my network request.

Step by step, build Retrofit in the HttpMethod class (add an image of the class) to briefly explain the two converters.

Combine rxJava to create a request Observable, or observed. Templates for setting request data are supported here. When WE say observed, let’s explain the observed and the observer. An important concept in RXJava is the observer pattern.

An Observable is a button, subscriber is onclickListener. So what is their setOnclickListener method? We’ll talk about that later.

Once the observer is created, we need to make some subscriptions. RxJava handles the issue of the observed and the observer’s execution thread perfectly using the subscribeOn and observeOn methods.

HTTP requests without using a framework we do when we need new one thread, and then began to request, because the network request is time-consuming operation, and use the rxjava everything changed just one line of code switching thread scheduling, and switch to the main thread is similar to the handler before operation, because the UI is not completed the child thread operation. Now, there’s a lot of magic in this, because it used to be so many lines of thread code and headler code, now it’s two lines, and it’s still a chain call, so it’s very simple and it’s very logical.

Ok, now to encapsulate the request method, we build the Retrofit object, set the request parameters, pass them as a map, and instantiate an Observable of the network request and convert the base data type to a concrete data type using the Map modifier. Subscriptions, and then were observed and the observer like button. SetonclickListener (). You can see that in my map method, I’m instantiating a class called HttpFunc, so let me show you what this class does.

I’ve defined an internal class in HttpMethod that implements the Func1 interface to make it easy to do some uniform processing of the data, separate out the specific parts of the data we care about, and handle requested exceptions. Func1 is a return value interface to RXJava to implement a callback with data.


How to use it?

Here I pass in two objects, a listener for the Model and an observer for the network request. How do they work?

Let’s start with the custom observer, which is a button-like onClickListener that inherits rxJava subscriber(observer), where I’ve overridden the parent class’s methods for the extension. Then instantiate the custom listener passed in for easy listening on data.

This is the model data listener DEFINED by me, which can listen to the specific data data concerned by the interface and the exceptions of network requests. It’s like layer after layer of data that we care about.


Finally, let’s compare the before and after code.


Volley request code before transformation


Retrofit+Rxjava code after modification




Finally, let’s take a look at the code before and after. It looks a little bit more code, but it’s stable, logical, and easy to extend, if you want to add interceptors, etc. The stability is that if there is an exception, RxJava onError method will be executed, which is convenient for us to deal with the exception of the data, do not have to worry about bad data from the server, resulting in a program crash, a server exception, you can throw the pan to the server.

It can do more than that, it can also do link requests, upload files and a lot of complicated logic.

We all face requirements changes and code changes at work; However, you will find that using RxJava in a way that reduces the probability of bugs and makes it easier to maintain even if different people change it. I’m using just the tip of the iceberg here. RxJava exists for more than just web requests; RxJava actually embodies the idea that all operations on the data are done on the stream, and only the data that the observer is interested in is returned. And then you get rid of all the anomalies, all the extra data.


The end of the


I used to look at my confusing if, else, and so on code, and it took me a while to figure out the logic and how important it was to write code coherently. The combination of RxJava and Retrofit will allow us to write code in a very clear and methodical way. The amount of code will increase, but the clarity of logic is the most important. My encapsulation of the request framework is definitely not the optimal scheme, and there are defects, I hope we can discuss more, learn from each other.

Author’s Brief Address:

http://www.jianshu.com/u/264fe9ae8b15

Source code address:

https://github.com/JenningsMST/RetrofitRxjavaSample

Share a blog: https://gank.io/post/56e80c2c677659311bed9841


Click “Read original” to jump to the source address