1. 程式人生 > >框架】之Retrofit+RxJava的使用

框架】之Retrofit+RxJava的使用

前幾天分別對Retrofit和RxJava進行了總結,這個帖子打算把Retrofit結合RxJava使用的方法總結以下。有還不瞭解Retrofit或RxJava的朋友可以參考下面的帖子學習~

首先匯入依賴:

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    testCompile 'junit:junit:4.12'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
    compile 'io.reactivex:rxjava:1.2.2'
    compile 'io.reactivex:rxandroid:1.2.1'
}
然後新增許可權:
<uses-permission android:name="android.permission.INTERNET" />

在貼出程式碼之前先宣告一下,這個帖子裡面用到的案例和Retrofit的帖子中用到的案例是同一個。

程式碼:

兩者結合的程式碼(未封裝):

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(SharedData.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        RetrofitService service = retrofit.create(RetrofitService.class);

        Observable<InfoData> observable = service.getInfoData();

        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<InfoData>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(InfoData infoData) {
                        Toast.makeText(MainActivity.this, infoData.getName(), Toast.LENGTH_SHORT).show();
                    }
                });


兩者結合的程式碼(封裝):

封裝好的工具類:

import com.example.itgungnir.testretrofit_rxjava.share.SharedData;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 網路訪問的工具類
 */
public class HttpUtil {
    private static HttpUtil instance;

    private Retrofit retrofit;

    private HttpUtil() {
        this.instance = this;
        this.retrofit = new Retrofit.Builder()
                .baseUrl(SharedData.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
    }

    private static HttpUtil getInstance() {
        if (instance == null) {
            synchronized (HttpUtil.class) {
                if (instance == null) {
                    return new HttpUtil();
                }
            }
        }
        return instance;
    }

    public static <T> T getService(Class<T> c) {
        return getInstance().retrofit.create(c);
    }

    public static <T> void init(Observable<T> observable, Subscriber<T> subscriber) {
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }
}
在主執行緒中呼叫工具類:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        HttpUtil.init(HttpUtil.getService(RetrofitService.class).getInfoData(), new Subscriber<InfoData>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(InfoData infoData) {
                Toast.makeText(MainActivity.this, infoData.getName(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}



執行結果: