我已经注射了sharedPreference
in ViewModel
.
我可以在嵌入 Coroutine 作用域时使用 Android 特定资源吗?当 ViewModel 失去作用域时,Coroutine 作用域会自动挂起。
我的意思是,如果我们添加 viewModel 启动范围,可以在 ViewModel 中使用preferende吗?
CoroutineScope 会跟踪它创建的所有协程。因此,如果取消一个作用域,就会取消它创建的所有协程
@ContributesViewModel
class SplashViewModel @Inject constructor(private val prefs: PrefStore) : BaseViewModel() {
val onMoveToNext = ClassLiveData()
init {
scope.launch {
val activity = if(prefs.isLoggedIn()) HomeActivity::class
else OnBoardingActivity::class
onMoveToNext.postValue(activity)
}
}
///fun saveDeviceID(id:String) = prefs.setDeviceID(id)
//fun createErrorCodeHash() ={}
fun getIsLoggedIn():Boolean = prefs.isLoggedIn()
fun setSecondTimeLogin(boolean: Boolean) = prefs.setIsSecondTimeLogin(boolean)
}
Where
abstract class BaseViewModel: ViewModel() {
private val job = Job()
val scope = CoroutineScope(Dispatchers.IO + job)
override fun onCleared() {
super.onCleared()
job.cancel()
}
}
类实时数据在哪里
typealias ClassLiveData = MutableLiveData<KClass<*>>
并在SplashActivity中调用它
viewModel.onMoveToNext.listen(this) {
Handler().postDelayed({
val intent = Intent(this, it.java)
intent.putExtra("Role", "LOGIN")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
}, 2000)