Combination of Retrofit and RxJava

Keywords: Retrofit OkHttp Google network

These two frameworks are very popular now. The combination of strong and strong forces makes our efficiency more direct

First, we need to import the dependencies

    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
    implementation 'io.reactivex.rxjava2:rxjava:2.0.2'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'

Next, we are going to splice our data

Methods in api

This is to encapsulate the network request class. We use static inner class encapsulation to make our encapsulation more concise

public class HttpUtils {

    public final Api api;

    private HttpUtils() {
        Retrofit retrofit = new Retrofit
                .Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(Constant.URL)
                .build();
        api = retrofit.create(Api.class);
    }


    private static class Instance{
        private static HttpUtils httpUtils = new HttpUtils();
    }

    public static HttpUtils getInstance(){
        return Instance.httpUtils;
    }

Next, we use our rx asynchrony to complete, and reasonably use the subscription relationship between the observer and the observed to request

   Observable<UserInfo> login = HttpUtils.getInstance().api.login("XXXXX", "XXXXX");
        login.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UserInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(UserInfo userInfo) {
                       
                        Log.e("This is a print log==","Here is the requested data");
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

 

Posted by 25lez25 on Tue, 17 Dec 2019 10:14:25 -0800