Last active
March 8, 2022 03:44
-
-
Save flyer88/5d7129fc2ca9010ff6109a81157fbafa to your computer and use it in GitHub Desktop.
如何实现 RxJava 的链式调用 -- map 方法的实现
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface Api{ | |
void queryPhoto(String query,QueryCallback QueryCallback); | |
interface QueryCallback{ | |
void onQuerySuccess(List<Photo> photoList); | |
void onQueryFailed(Exception e); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PhotoUtils{ | |
Api mApi; | |
public void handlePhotoSync(){ | |
mApi.queryPhoto("flyer", new Api.QueryCallback() { | |
@Override | |
public void onQuerySuccess(List<Photo> photoList) { | |
Photo photo = getBestPhoto(photoList); | |
String imgUrl = photo.getUrl(); | |
} | |
@Override | |
public void onQueryFailed(Exception e) { | |
ToastUtils.show(e); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
整个任务如何运行
解释代码,第一个
map
方法 返还了一个RxJob<Photo>
对象,第二个map
返还了一个RxJob<String>
对象,第三个doJob
方法触发整个任务doJob
方法触发的第一个方法是urlJob
中的doJob
方法,由于urlJob
对象是由map
方法创建的因此,在执行
ToastUtils.show(s)
方法之前,会先执行bestPhotoJob.doJob()
同样,
queryPhotoJob.doJob()
也会执行在bestPhotoJob.doJob()
方法之前因此整体过程就是
queryPhotoJob.doJob()
—>bestPhotoJob.doJob()
—>urlJob.doJob()
而这执行过程中,
R mapped = func.call(T)
会先被调用,因此单个RxJob
调用链如下:queryPhotoJob.doJob()
:mApi.query
—>func.call(t)
—>getBestPhoto(photoList)
bestPhotoJob.doJob()
:func.call(t)
—>photo.getUrl()
urlJob.doJob()
:ToastUtil.show()
比较炫酷的写法如下: