Rxjava实现网络请求
与OkHttp结合进行网络通信
OkHttp是一个第三方类库,用于Android中请求网络。
OkHttp官网
github源码
实现:
1)通过 Observable.create() 方法,调用 OkHttp 网络请求;
2)通过 map 操作符集合 gson,将 Response 转换为 bean 类;
3)调度线程,在子线程中进行耗时操作任务,在主线程中更新 UI ;
代码:
Observable.create(new ObservableOnSubscribe<Response>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Response> e) throws Exception {
Builder builder = new Builder()
.url("http://fy.iciba.com/ajax.php?a=fy&f=auto&t=auto&w=hello%20world")
.get();
Request request = builder.build();
Call call = new OkHttpClient().newCall(request);
Response response = call.execute();
e.onNext(response);
}
}).map(new Function<Response, Translation>() {
@Override
public Translation apply(@NonNull Response response) throws Exception {
Log.e(TAG, "map 线程:" + Thread.currentThread().getName() + "\n");
if (response.isSuccessful()) {
ResponseBody body = response.body();
if (body != null) {
Log.e(TAG, "map:Json转换前:" + response.body());
return new Gson().fromJson(body.string(), Translation.class);
}
}
return null;
}
}).observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Translation>() {
@Override
public void accept(@NonNull Translation data) throws Exception {
Log.e(TAG, "subscribe 线程:" + Thread.currentThread().getName() + "\n");
Log.e(TAG, "成功:" + data.getContent().getOut() + "\n");
}
});