Android: This is a very detailed practical chapter on the combination of MVP + Rxjava 2.0 + Retrofit 2.0 for example RecyclerView

Keywords: Android Retrofit Attribute Java

MVP + Rxjava 2.0 + Retrofit 2.0 is now a very popular combination
MVP believes that you have learned a lot about the theory in the major websites and the articles of the big guys.
MVP is actually M-tier requesting data in P-tier for M-tier and V-tier interactive V-tier to get data and display data.
For example, the mother jackal goes to prey on the food and returns to the nest to feed the baby wolf.
Jackal mother is M P, wolf nest V, wolf baby
The key point of MVP is that if you are not familiar with interface callback, you'd better learn to practice interface callback first.

So MVP+Rxjava 2.0+Retrofit 2.0 has two important classes in actual combat projects.

Cantranct: The general classes of the three interfaces of mvp are clearly and normatively placed in this class.
APIInterface: The general class of API interfaces Retrofit requests all the interfaces in this
The overall subcontracting of the project is as follows:

Here is a detailed introduction of MVP + Rxjava 2.0 + Retrofit 2.0 + Recycler View
Interface: http://api.kkmh.com/v1/daily/comic_lists/0?since=0&gender=0

The following code comments! Very detailed annotation of each interface! Method in each interface! Role

Network permissions:

 <uses-permission android:name="android.permission.INTERNET" />

Dependence:

 //Retrofit dependency
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.okhttp3:okhttp:3.9.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
    //RxJava2 dependencies
    compile 'io.reactivex.rxjava2:rxjava:+'
    compile 'io.reactivex.rxjava2:rxandroid:+'
    compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'
    //glide dependence
    compile 'com.github.bumptech.glide:glide:3.7.0'
    //RecyclerView dependency
    compile 'com.android.support:recyclerview-v7:26.1.0'

Create api packages and create APIInterface interfaces

import com.example.mydemo.bean.MyBean;

import io.reactivex.Observable;
import retrofit2.http.GET;

/**
 * Created by wxy on 2017/12/6.
 * API All requests are written in this class
 */

public interface APIInterface {
    //Interface address
    //String url = "http://api.kkmh.com/v1/daily/comic_lists/0?since=0&gender=0";

    //get request
    @GET("v1/daily/comic_lists/0?since=0&gender=0")
    Observable<MyBean> getMyData();  //Bean classes in generics
}

Create cantranct packages and create Cantranct classes

mport com.example.mydemo.bean.MyBean;

import java.util.List;

/**
 * Created by wxy on 2017/12/6.
 * mvp General Class of Interfaces
 */

public class Cantranct {
    //M-Layer Interface and Method: Data Acquisition
    public interface IModel {
        //The method and method parameters of M-tier acquisition request data are the following interface objects
        void model(CallBack callBack);

        //The method of storing the data in the interface after the M layer gets it and then calls back the data to the P layer.
        interface CallBack {
            //The parameters of the method save the data acquired by m layer and then call back to P layer.
            void callData(List<MyBean.DataBean.ComicsBean> comics);
        }
    }

    //P-layer interface and method: logic such as interaction between M and V layers (in fact, both P-layer and Write-Free interfaces can be unified and standardized by interface)
    public interface IPresenter {
        void presenter();
    }

    //V-Layer Interface: Receiving Data and Displaying Data
    public interface IView {
        //The parameters of the method are used to receive the data acquired in layer P through layer M.
        void view(List<MyBean.DataBean.ComicsBean> comics);
    }

}

Create model packages and create model classes

import com.example.mydemo.api.APIInterface;
import com.example.mydemo.bean.MyBean;
import com.example.mydemo.cantranct.Cantranct;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by wxy on 2017/12/6.
 * M Layer requests data and calls back the data to Layer P
 */

public class Model implements Cantranct.IModel {
    private String baseUrl = "http://api.kkmh.com/";

    @Override        //This callback interface is used to store data in the P layer and transfer data to the V layer.
    public void model(final CallBack callBack) {

        Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl)//Add baseurl
                //Add Rxjava
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        //Create Add API Classes
        APIInterface apiInterface = retrofit.create(APIInterface.class);
        //Call the getMyData request method in the API
        apiInterface.getMyData()
                //Specify the observer thread
                .subscribeOn(Schedulers.io())
                //Specify observer threads
                .observeOn(AndroidSchedulers.mainThread())
                //Subscribe
                .subscribe(new Observer<MyBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(MyBean myBean) {
                        if (myBean != null) {
                            List<MyBean.DataBean.ComicsBean> data = myBean.getData().getComics();
                            myBean.getData().getComics();
                            //Save the data to the method of the callback interface after the request to the data                
                            //Used to call back data to layer P and to give data to layer V in layer P
                            callBack.callData(data);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


}

Create Presenter packages and create Presenter classes

import com.example.mydemo.bean.MyBean;
import com.example.mydemo.cantranct.Cantranct;
import com.example.mydemo.model.Model;

import java.util.List;

/**
 * Created by wxy on 2017/12/6.
 * P Layer logic for the interaction between M and V mainly transfers the data acquired by M to V.
 */

public class Presenter implements Cantranct.IPresenter {
    //Creating M-tier objects
    private Model model;
    //Objects to create a V-tier interface
    private Cantranct.IView iView;

    //The parameter of the construction method is the interface object of V layer.
    public Presenter(Cantranct.IView iView) {
        //The class presenting the data will pass itself in when the V interface creates the P layer. That is to say, the P layer and the class presenting the data use the same V layer interface. Naturally, the data in the V layer interface method can be shared.
        this.iView = iView;
        //Naturally running the M-tier implementation's request data method when creating the M-tier now understands that the data has been requested.
        model = new Model();
    }

    @Override//Interaction between M and V layers in this method
    public void presenter() {
        //M layer creates callback interface object to save data. The parameter of method in this interface is data collection.
        model.model(new Cantranct.IModel.CallBack() {
            @Override
            public void callData(List<MyBean.DataBean.ComicsBean> data) {
                //Then the data is saved with the V-layer interface object and displayed in the V-layer.
                iView.view(data);
            }
        });

    }
}

Create View Package and Create Activity Class

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.example.mydemo.Adapter.MyAdapter;
import com.example.mydemo.R;
import com.example.mydemo.bean.MyBean;
import com.example.mydemo.cantranct.Cantranct;
import com.example.mydemo.presenter.Presenter;

import java.util.List;

/**
 * V Layer P gets the data from Layer P and displays the data.
 * Implementing V-Layer Interface
 */
public class MainActivity extends AppCompatActivity implements Cantranct.IView {

    private RecyclerView recy;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Get controls
        initView();
        //Creating P-layer object input itself is because the constructor of P-layer is IView interface. This class implements IView interface. After passing itself in, the V-interface which interacts with P-layer obtains data from the V-layer interface method implemented by this class can be used.
        Presenter presenter = new Presenter(this);
        presenter.presenter();
    }

    @Override//Data acquired from layer P and data requested from layer M in layer P
    public void view(List<MyBean.DataBean.ComicsBean> data) {
        MyAdapter adapter = new MyAdapter(this, data);
        recy.setAdapter(adapter);
        recy.setLayoutManager(new LinearLayoutManager(this));
    }

    private void initView() {
        recy = (RecyclerView) findViewById(R.id.recy);
    }
}

This is the whole MVP+Rxjava+Retrofit combines with practice or after reading the code, and then combines with the theory you have seen, a good stroke or a pen and paper drawing can understand a deeper point. Here are the adapter classes and layout files of RecyclerView. To practice this Demo, you can copy the following.

Bean classes don't have to be copied to create their own
activity_main

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mydemo.view.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recy"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>

</RelativeLayout>

item

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">

    <ImageView
        android:id="@+id/im"
        android:layout_width="200dp"
        android:layout_height="150dp"
        android:scaleType="fitXY"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="15dp"
        android:text="aaaaaa"
        />
</LinearLayout>

MyAdapater

import android.content.Context;
import android.media.Image;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.mydemo.R;
import com.example.mydemo.bean.MyBean;

import java.util.List;

/**
 * Created by wxy on 2017/12/6.
 */

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHodel> {
    private Context context;
    private List<MyBean.DataBean.ComicsBean> data = null;

    public MyAdapter(Context context, List<MyBean.DataBean.ComicsBean> data) {
        this.context = context;
        this.data = data;
    }

    @Override
    public MyViewHodel onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = View.inflate(context, R.layout.item, null);
        return new MyViewHodel(view);
    }

    @Override
    public void onBindViewHolder(MyViewHodel holder, int position) {
        Glide.with(context).load(data.get(position).getCover_image_url()).into(holder.im);
        holder.tv.setText(data.get(position).getTopic().getDescription());
    }

    @Override
    public int getItemCount() {
        return data.size() != 0 ? data.size() : 0;
    }

    static class MyViewHodel extends RecyclerView.ViewHolder {

        public final ImageView im;
        public final TextView tv;

        public MyViewHodel(View itemView) {
            super(itemView);
            im = itemView.findViewById(R.id.im);
            tv = itemView.findViewById(R.id.tv);

        }
    }

}

The final results are as follows

Don't look at so many theories to practice, even if you grope and practice alone slowly will clear up.
Below are links to Rxjava and Retrofit
Simple Use of Retrofir 2.0
Rxjava
Rxjava 2.0 and Retrofit 2.0 are used together

Posted by mote on Sat, 15 Dec 2018 15:54:04 -0800