Skip to content

Instantly share code, notes, and snippets.

@flyer88
Last active March 8, 2022 03:44
Show Gist options
  • Save flyer88/e7a1841185a3758acd7bc68c0d7a8cd8 to your computer and use it in GitHub Desktop.
Save flyer88/e7a1841185a3758acd7bc68c0d7a8cd8 to your computer and use it in GitHub Desktop.
如何实现 RxJava 的链式调用--异步中的异步 flatMap
public interface Api{
void queryPhoto(String query,QueryCallback QueryCallback);
void store(Photo photo,StoreCallback storeCallback);
interface QueryCallback{
void onQuerySuccess(List<Photo> photoList);
void onQueryFailed(Exception e);
}
interface StoreCallback{
void onCatStored(Uri uri);
void onStoredFailed(Exception e);
}
}
RxJob<List<Photo>> queryPhotoJob = new RxJob<List<Photo>>(){
@Override
public void doJob(final RxCallback<List<Photo>> rxCallback) {
mApi.queryPhoto("flyer", new Api.QueryCallback() {
@Override
public void onQuerySuccess(List<Photo> photoList) {
rxCallback.onNext(photoList);
}
@Override
public void onQueryFailed(Exception e) {
rxCallback.onError(e);
}
});
}
};
};
RxJob<List<Photo>> storePhotoJob = new RxJob<Uri>() {
@Override
public void doJob(RxCallback<Uri> rxCallback) {
mApi.store(photo, new Api.StoreCallback() {
@Override
public void onCatStored(Uri uri) {
rxCallback.onNext(uri);
}
@Override
public void onStoredFailed(Exception e) {
rxCallback.onError(e);
}
});
}
};
queryPhotoJob.map(photoList -> { return getBestPhoto(photoList);})
.flatMap(photo -> { return storePhotoJob;} )
.map(photo -> {return photo.getUrl();})
.doJob(new RxCallback<String>() {
@Override
public void onNext(String s) {
ToastUtils.show(s);
}
@Override
public void onError(Exception e) {
ToastUtils.show(e);
}
});
public abstract class RxJob<T>{
public abstract void doJob(RxCallback<T> rxCallback){}
public RxJob map(){
final RxJob<T> curJob = this;
return new RxJob<R>() {
@Override
public void doJob(final RxCallback<R> rxCallback) {
curJob.doJob(new RxCallback<T>() {
@Override
public void onNext(T t) {
R mapped = func.call(t);
rxCallback.onNext(mapped);
}
@Override
public void onError(Exception e) {
rxCallback.onError(e);
}
});
}
};
}
public RxJob flatMap(){...};
}
@flyer88
Copy link
Author

flyer88 commented May 26, 2017

========================================================

最后

记录一些 RxJava 相关的文章内容

RxJava 中的 contactMap 和 flatMap 区别

========================================================

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment