RxJava가 안드로이드 모바일 개발에서의 실전 응용 2
12673 단어 [RxJava 실전]RxJava 실전
판권 성명: 본고는 문심문룡의 블로그에서 나온 것으로 오리지널 내용에 속하므로 전재는 출처를 밝혀 주십시오.https://blog.csdn.net/geduo_83/article/details/89740000
문서 목록
Observable
.create(new ObservableOnSubscribe() {
@Override
public void subscribe(@NonNull ObservableEmitter e) throws Exception {
Builder builder = new Builder()
.url("http://api.avatardata.cn/MobilePlace/LookUp?key=ec47b85086be4dc8b5d941f5abd37a4e&mobileNumber=13021671512")
.get();
Request request = builder.build();
Call call = new OkHttpClient().newCall(request);
Response response = call.execute();
e.onNext(response);
}
})
.map(new Function() {
@Override
public MobileAddress apply(@NonNull Response response) throws Exception {
Log.e(TAG, "map :" + Thread.currentThread().getName() + "
");
if (response.isSuccessful()) {
ResponseBody body = response.body();
if (body != null) {
Log.e(TAG, "map: :" + response.body());
return new Gson().fromJson(body.string(), MobileAddress.class);
}
}
return null;
}
})
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(new Consumer() {
@Override
public void accept(@NonNull MobileAddress s) throws Exception {
Log.e(TAG, "doOnNext :" + Thread.currentThread().getName() + "
");
mRxOperatorsText.append("
doOnNext :" + Thread.currentThread().getName() + "
");
Log.e(TAG, "doOnNext: :" + s.toString() + "
");
mRxOperatorsText.append("doOnNext: :" + s.toString() + "
");
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer() {
@Override
public void accept(@NonNull MobileAddress data) throws Exception {
Log.e(TAG, "subscribe :" + Thread.currentThread().getName() + "
");
mRxOperatorsText.append("
subscribe :" + Thread.currentThread().getName() + "
");
Log.e(TAG, " :" + data.toString() + "
");
mRxOperatorsText.append(" :" + data.toString() + "
");
}
}, new Consumer() {
@Override
public void accept(@NonNull Throwable throwable) throws Exception {
Log.e(TAG, "subscribe :" + Thread.currentThread().getName() + "
");
mRxOperatorsText.append("
subscribe :" + Thread.currentThread().getName() + "
");
Log.e(TAG, " :" + throwable.getMessage() + "
");
mRxOperatorsText.append(" :" + throwable.getMessage() + "
");
}
});
2. 캐시를 먼저 읽고 캐시에 데이터가 없으면 네트워크 요청을 통해 데이터를 얻은 후 UI 업데이트
Observable cache = Observable
.create(new ObservableOnSubscribe() {
@Override
public void subscribe(@NonNull ObservableEmitter e) throws Exception {
Log.e(TAG, "create :"+Thread.currentThread().getName() );
FoodList data = CacheManager.getInstance().getFoodListData();
// concat , onComplete Observable
if (data != null){ // , ,
isFromNet = false;
Log.e(TAG, "
subscribe: :" );
runOnUiThread(new Runnable() {
@Override
public void run() {
mRxOperatorsText.append("
subscribe: :
");
}
});
e.onNext(data);
}else {
isFromNet = true;
runOnUiThread(new Runnable() {
@Override
public void run() {
mRxOperatorsText.append("
subscribe: :
");
}
});
Log.e(TAG, "
subscribe: :" );
e.onComplete();
}
}
});
Observable network = Rx2AndroidNetworking.get("http://www.tngou.net/api/food/list")
.addQueryParameter("rows",10+"")
.build()
.getObjectObservable(FoodList.class);
// Observable
Observable
.concat(cache,network)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer() {
@Override
public void accept(@NonNull FoodList tngouBeen) throws Exception {
Log.e(TAG, "subscribe :"+Thread.currentThread().getName() );
if (isFromNet){
mRxOperatorsText.append("accept : :
");
Log.e(TAG, "accept : :
"+tngouBeen.toString() );
CacheManager.getInstance().setFoodListData(tngouBeen);
}
mRxOperatorsText.append("accept: :" + tngouBeen.toString()+"
");
Log.e(TAG, "accept: :" + tngouBeen.toString());
}
}, new Consumer() {
@Override
public void accept(@NonNull Throwable throwable) throws Exception {
Log.e(TAG, "subscribe :"+Thread.currentThread().getName() );
Log.e(TAG, "accept: :"+throwable.getMessage() );
mRxOperatorsText.append("accept: :"+throwable.getMessage()+"
");
}
});
3. 여러 네트워크 요청을 순차적으로 의존
Rx2AndroidNetworking.get("http://www.tngou.net/api/food/list")
.addQueryParameter("rows", 1 + "")
.build()
.getObjectObservable(FoodList.class) // , FootList
.subscribeOn(Schedulers.io()) // io
.observeOn(AndroidSchedulers.mainThread()) //
.doOnNext(new Consumer() {
@Override
public void accept(@NonNull FoodList foodList) throws Exception {
//
Log.e(TAG, "accept: doOnNext :" + foodList.toString());
mRxOperatorsText.append("accept: doOnNext :" + foodList.toString()+"
");
}
})
.observeOn(Schedulers.io()) // io
.flatMap(new Function>() {
@Override
public ObservableSource apply(@NonNull FoodList foodList) throws Exception {
if (foodList != null && foodList.getTngou() != null && foodList.getTngou().size() > 0) {
return Rx2AndroidNetworking.post("http://www.tngou.net/api/food/show")
.addBodyParameter("id", foodList.getTngou().get(0).getId() + "")
.build()
.getObjectObservable(FoodDetail.class);
}
return null;
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer() {
@Override
public void accept(@NonNull FoodDetail foodDetail) throws Exception {
Log.e(TAG, "accept: success :" + foodDetail.toString());
mRxOperatorsText.append("accept: success :" + foodDetail.toString()+"
");
}
}, new Consumer() {
@Override
public void accept(@NonNull Throwable throwable) throws Exception {
Log.e(TAG, "accept: error :" + throwable.getMessage());
mRxOperatorsText.append("accept: error :" + throwable.getMessage()+"
");
}
});
4. 여러 인터페이스의 데이터 업데이트 UI 결합
Observable observable1 = Rx2AndroidNetworking.get("http://api.avatardata.cn/MobilePlace/LookUp?key=ec47b85086be4dc8b5d941f5abd37a4e&mobileNumber=13021671512")
.build()
.getObjectObservable(MobileAddress.class);
Observable observable2 = Network.getGankApi()
.getCategoryData("Android",1,1);
Observable.zip(observable1, observable2, new BiFunction() {
@Override
public String apply(@NonNull MobileAddress mobileAddress, @NonNull CategoryResult categoryResult) throws Exception {
return " : :"+mobileAddress.getResult().getMobilearea()+" :"+categoryResult.results.get(0).who;
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer() {
@Override
public void accept(@NonNull String s) throws Exception {
Log.e(TAG, "accept: :" + s+"
");
}
}, new Consumer() {
@Override
public void accept(@NonNull Throwable throwable) throws Exception {
Log.e(TAG, "accept: :" + throwable+"
");
}
});
5. 간격 퀘스트 심장 박동 실현
private Disposable mDisposable;
@Override
protected void doSomething() {
mDisposable = Flowable.interval(1, TimeUnit.SECONDS)
.doOnNext(new Consumer() {
@Override
public void accept(@NonNull Long aLong) throws Exception {
Log.e(TAG, "accept: doOnNext : "+aLong );
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer() {
@Override
public void accept(@NonNull Long aLong) throws Exception {
Log.e(TAG, "accept: :"+aLong );
mRxOperatorsText.append("accept: :"+aLong +"
");
}
});
}
/**
*
*/
@Override
protected void onDestroy() {
super.onDestroy();
if (mDisposable != null){
mDisposable.dispose();
}
}