Xenex
09/20/2021, 2:56 PMLuke
09/20/2021, 3:05 PMNonCancellable
context? But I'm not sure that fixes the NPEstojan
09/20/2021, 3:08 PMonPause
)Rick Busarow
09/20/2021, 3:13 PMXenex
09/20/2021, 4:19 PMoverride fun onPause() {
super.onPause()
viewModel.onMapStopping()
}
VM:
fun onMapStopping() = viewModelScope.launch {
preferencesManager.updateMapLocation(cameraPosition.value!!)
}
PrefManager:
suspend fun updateMapLocation(cameraPosition: CameraPosition) {
datastore.edit { preferences ->
preferences[PreferenceKeys.KEY] = Gson().toJson(cameraPosition)
}
}
It's working normally fine without problems, but some users got the exception. Any suggestions now?Rick Busarow
09/20/2021, 4:22 PMviewModelScope
is not sufficient. Your PrefManager
should just have its own CoroutineScope so that those writes aren’t interrupted.Xenex
09/20/2021, 4:24 PMRick Busarow
09/20/2021, 4:32 PMclass PrefsManager(
val coroutineScope: CoroutineScope,
val datastore: DataStore
) {
fun updateMapLocation(cameraPosition: CameraPosition): Job {
return coroutineScope.launch {
datastore.edit { preferences ->
preferences[PreferenceKeys.KEY] = Gson().toJson(cameraPosition)
}
}
}
}
If you’re using Dagger or Koin, you can inject the CoroutineScope. Otherwise just initialize it yourself as a property of the class.
You don’t need to make it non-cancellable or global. The scope won’t be cancelled unless you cancel it.Xenex
09/20/2021, 4:34 PM