前言:kotlin挂起函数+ViewModel,使异步如此简单。
案例:(1)下载文件(2)保存文件
viewModelScope.launch {
kotlin.runCatching {
//下载文件
HomeRespository().downFile(billLogoUrl)
}.onSuccess {
kotlin.runCatching {
//保存文件
val fileName = billLogoUrl.substring(billLogoUrl.lastIndexOf("/"))
FileUtil.saveFile(it.byteStream(), FileUtil.PATH, fileName)
}.onSuccess {
AppPrefsUtils.putBoolean(AppPrefsUtils.BILL_LOGO_DOWN_SUCCESS, true)
}.onFailure {
AppPrefsUtils.putBoolean(AppPrefsUtils.BILL_LOGO_DOWN_SUCCESS, false)
}
}.onFailure {
AppPrefsUtils.putBoolean(AppPrefsUtils.BILL_LOGO_DOWN_SUCCESS, false)
}
}
class HomeRespository {
private val mService = RetrofitFactory.instance.create(BaseConstant.SERVICE_HOST).create(
HomeApi::class.java
)
suspend fun downFile(url: String): Resp

最低0.47元/天 解锁文章
7373

被折叠的 条评论
为什么被折叠?



