-
Notifications
You must be signed in to change notification settings - Fork 411
/
ContinueCoroutineWhenUserLeavesScreenViewModel.kt
49 lines (40 loc) 路 1.65 KB
/
ContinueCoroutineWhenUserLeavesScreenViewModel.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.lukaslechner.coroutineusecasesonandroid.usecases.coroutines.usecase14
import androidx.lifecycle.viewModelScope
import com.lukaslechner.coroutineusecasesonandroid.base.BaseViewModel
import kotlinx.coroutines.launch
class ContinueCoroutineWhenUserLeavesScreenViewModel(
private var repository: AndroidVersionRepository
) : BaseViewModel<UiState>() {
// more information in this blogpost about "Coroutines & Patterns for work that shouldn't
// be cancelled" =>
// https://medium.com/androiddevelopers/coroutines-patterns-for-work-that-shouldnt-be-cancelled-e26c40f142ad
fun loadData() {
uiState.value = UiState.Loading.LoadFromDb
viewModelScope.launch {
val localVersions = repository.getLocalAndroidVersions()
if (localVersions.isNotEmpty()) {
uiState.value =
UiState.Success(DataSource.Database, localVersions)
} else {
uiState.value =
UiState.Error(DataSource.Database, "Database empty!")
}
uiState.value = UiState.Loading.LoadFromNetwork
try {
uiState.value = UiState.Success(
DataSource.Network,
repository.loadAndStoreRemoteAndroidVersions()
)
} catch (exception: Exception) {
uiState.value = UiState.Error(DataSource.Network, "Network Request failed")
}
}
}
fun clearDatabase() {
repository.clearDatabase()
}
}
sealed class DataSource(val name: String) {
object Database : DataSource("Database")
object Network : DataSource("Network")
}