-
Notifications
You must be signed in to change notification settings - Fork 240
Description
问题描述
新版的ViewModle已经没有了setTagIfAbsent(),请作者更新。
ViewModle2.7.0以后就它找不到 androidx.lifecycle.ViewModel 类里的 setTagIfAbsent 方法。错误提示
ava.lang.NoSuchMethodError: No virtual method setTagIfAbsent(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object; in class Landroidx/lifecycle/ViewModel; or its super classes (declaration of 'androidx.lifecycle.ViewModel' appears in /data/app/~~VS-mLg3cVe2tVd1oHBjlDQ
期望行为
更新ViewModle的基础库,并且更新以下三个扩展函数。
fun ViewModel.scopeLife(
dispatcher: CoroutineDispatcher = Dispatchers.Main,
block: suspend CoroutineScope.() -> Unit
): AndroidScope {
val scope = AndroidScope(dispatcher = dispatcher).launch(block)
return setTagIfAbsent(scope.toString(), scope)
}
/**
-
在[ViewModel]被销毁时取消协程作用域以及其中的网络请求
-
具备网络错误全局处理功能, 其内部的网络请求会跟随其作用域的生命周期
*/
fun ViewModel.scopeNetLife(
dispatcher: CoroutineDispatcher = Dispatchers.Main,
block: suspend CoroutineScope.() -> Unit
): NetCoroutineScope {
val scope = NetCoroutineScope(dispatcher = dispatcher).launch(block)
return setTagIfAbsent(scope.toString(), scope)
}
/** 轮询器根据ViewModel生命周期自动取消 */
fun Interval.life(viewModel: ViewModel) = apply {
viewModel.setTagIfAbsent(toString(), this)
}
如何复现
新建一个工程,在ViewModle中请求网络,100%复现。使用这种方法请求。
fun fetchUserInfo() = scopeNetLife {
userInfo.value = Get(Api.GAME).await()
}
fork仓库并复现问题可以快速解决, 猜测只会让问题晦涩难懂, 耽误所有人时间
截图
异常堆栈信息或者手机截图/视频(拖拽到输入框即可上传)
版本
- Net:3.7.0
- OkHttp:
- Android:7.0.0
- Gradle: 8.12
- Android Studio: