I have injected sharedPreference in ViewModel.
Can I use android specific resource's while embedding Coroutine scope which automatically suspended when ViewModel loses scope.
I mean is it ok to use preferende in ViewModel if we add a viewModel launch scope
A CoroutineScope keeps track of all coroutines it creates. Therefore, if you cancel a scope, you cancel all coroutines it created
@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()
}
}
where ClassLiveData
typealias ClassLiveData = MutableLiveData<KClass<*>>
And called it in 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)