Skip to content

Instantly share code, notes, and snippets.

@shaohui10086
Last active November 18, 2019 05:51
Show Gist options
  • Save shaohui10086/2554ef92fa4e3ce701acde02567e750b to your computer and use it in GitHub Desktop.
Save shaohui10086/2554ef92fa4e3ce701acde02567e750b to your computer and use it in GitHub Desktop.
RxJava vs Coroutines
fun rxJavaExample(folders: List<File>) {
Observable.from(folders)
.flatMap((folder) -> { Observable.from(folder.listFiles()) })
.filter( (file) -> { file.getName().endsWith(".png") })
.map( (file) -> { getBitmapFromFile(file) })
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((Action1) (bitmap) -> { imageCollectorView.addImage(bitmap) });
}
fun coroutineExample(folders: List<File>) {
Dispatcher.IO.launch {
folders.fold(mutableListOf<File>(), { result, item -> result.allAll(item.listFiles()); result })
.filter { it.getName().endsWith(".png") }
.map { getBitmapFromFile(it) }
.forEach { with(Dispatchers.Main) { imageCollectorView.addImage(bitmap) }}
}
}
/**
* 输入是id列表
* 要全返回用户名列表
* 例如:[vistashao] -> [邵辉]
*/
fun rxjavaExample(ids: List<String>): Observable<List<String?>> {
val requests = ids.map { requestUserInfo(it) }
return Observable.zip(requests) { return@zip it.toList() }
.map { it.map { (it as? UserInfo)?.name } }
.observeOn(Schedulers.io())
}
fun coroutineExample(ids: List<String>): LiveData<List<String?>> {
val liveData = MutableLiveData<List<String?>>()
GlobalScope.launch {
val deferredJobs = ids.map {
async(Dispatchers.IO) {
val userInfo = requestUserInfo(it)
return@async userInfo.name
}
}
liveData.postValue(deferredJobs.awaitAll())
}
return liveData
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment