Better coroutine management

This commit is contained in:
Benoit Marty 2020-05-18 15:59:15 +02:00
parent 538bda329e
commit 28f8d9500e
2 changed files with 18 additions and 35 deletions

View file

@ -23,9 +23,6 @@ import androidx.core.content.edit
import androidx.preference.PreferenceManager
import im.vector.riotx.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.util.Locale
@ -258,19 +255,13 @@ object VectorLocale {
}
}
fun loadLocales(listener: Listener): Job {
return GlobalScope.launch(Dispatchers.Main) {
if (supportedLocales.isEmpty()) {
// init the known locales in background
withContext(Dispatchers.IO) {
initApplicationLocales()
}
suspend fun getSupportedLocales(): List<Locale> {
if (supportedLocales.isEmpty()) {
// init the known locales in background
withContext(Dispatchers.IO) {
initApplicationLocales()
}
listener.onLoaded(supportedLocales)
}
}
interface Listener {
fun onLoaded(locales: List<Locale>)
return supportedLocales
}
}

View file

@ -16,6 +16,7 @@
package im.vector.riotx.features.settings.locale
import androidx.lifecycle.viewModelScope
import com.airbnb.mvrx.ActivityViewModelContext
import com.airbnb.mvrx.FragmentViewModelContext
import com.airbnb.mvrx.MvRxViewModelFactory
@ -26,23 +27,27 @@ import com.squareup.inject.assisted.AssistedInject
import im.vector.riotx.core.extensions.exhaustive
import im.vector.riotx.core.platform.VectorViewModel
import im.vector.riotx.features.settings.VectorLocale
import kotlinx.coroutines.Job
import java.util.Locale
import kotlinx.coroutines.launch
class LocalePickerViewModel @AssistedInject constructor(
@Assisted initialState: LocalePickerViewState
) : VectorViewModel<LocalePickerViewState, LocalePickerAction, LocalePickerViewEvents>(initialState),
VectorLocale.Listener {
) : VectorViewModel<LocalePickerViewState, LocalePickerAction, LocalePickerViewEvents>(initialState) {
@AssistedInject.Factory
interface Factory {
fun create(initialState: LocalePickerViewState): LocalePickerViewModel
}
private var loadingJob: Job? = null
init {
loadingJob = VectorLocale.loadLocales(this)
viewModelScope.launch {
val result = VectorLocale.getSupportedLocales()
setState {
copy(
locales = Success(result)
)
}
}
}
companion object : MvRxViewModelFactory<LocalePickerViewModel, LocalePickerViewState> {
@ -67,17 +72,4 @@ class LocalePickerViewModel @AssistedInject constructor(
VectorLocale.saveApplicationLocale(action.locale)
_viewEvents.post(LocalePickerViewEvents.RestartActivity)
}
override fun onLoaded(locales: List<Locale>) {
setState {
copy(
locales = Success(locales)
)
}
}
override fun onCleared() {
super.onCleared()
loadingJob?.cancel()
}
}