1.添加依赖
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.生成实体类
Api地址:
http://www.wanandroid.com/article/list/1/json
通过以上地址获取json 使用android studio 的GsonFormat工具生成Article类(内容过长就不贴了...)
3.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 获取数据
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.总结
Rxjava和Retrofit的新版和旧版的使用方式不同