RxJava +Retrofit 簡單使用

1.添加依賴java

compile 'com.squareup.retrofit2:converter-gson:2.3.0' compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' implementation 'io.reactivex.rxjava2:rxjava:2.2.0' implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'

2.生成實體類react

Api地址:android

http://www.wanandroid.com/article/list/1/json

經過以上地址獲取json 使用android studio 的GsonFormat工具生成Article類(內容過長就不貼了...)json

3.Api類api

 ... import io.reactivex.Observable; import retrofit2.http.GET; import retrofit2.http.Path; public interface Api { @GET("article/list/{index}/json") Observable<Article> getArticle(@Path("index") String index); }

4.activity 獲取數據app

import android.util.Log;
import com.djdsm.mystudyapp.R;
import com.djdsm.mystudyapp.home.base.BaseActivity;
import com.djdsm.mystudyapp.home.data.model.Article;
import com.djdsm.mystudyapp.home.data.remote.Api;

import io.reactivex.functions.Consumer;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.android.schedulers.AndroidSchedulers;

public class RxRetrofitActivity extends BaseActivity {
@Override
public int intiLayout() {
return R.layout.activity_rxretorfit;
}

...

@Override
public void initData() {
doRequestByRxRetrofit();
}

private void doRequestByRxRetrofit() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.wanandroid.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
Api api = retrofit.create(Api.class);
api.getArticle("1").subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Article>() {
@Override
public void accept(Article article) throws Exception {
//操做article...
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
Log.e(TAG, "獲取失敗");
}
});
}
}

5.總結ide

Rxjava和Retrofit的新版和舊版的使用方式不一樣工具

相關文章
相關標籤/搜索