Last active
          November 18, 2019 05:51 
        
      - 
      
- 
        Save shaohui10086/2554ef92fa4e3ce701acde02567e750b to your computer and use it in GitHub Desktop. 
    RxJava vs Coroutines
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | 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