-
Notifications
You must be signed in to change notification settings - Fork 409
/
RoomAndCoroutinesViewModel.kt
49 lines (42 loc) 路 1.6 KB
/
RoomAndCoroutinesViewModel.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.usecase8
import androidx.lifecycle.viewModelScope
import com.lukaslechner.coroutineusecasesonandroid.base.BaseViewModel
import com.lukaslechner.coroutineusecasesonandroid.mock.MockApi
import kotlinx.coroutines.launch
class RoomAndCoroutinesViewModel(
private val api: MockApi,
private val database: AndroidVersionDao
) : BaseViewModel<UiState>() {
fun loadData() {
uiState.value = UiState.Loading.LoadFromDb
viewModelScope.launch {
val localVersions = database.getAndroidVersions()
if (localVersions.isEmpty()) {
uiState.value =
UiState.Error(DataSource.DATABASE, "Database empty!")
} else {
uiState.value =
UiState.Success(DataSource.DATABASE, localVersions.mapToUiModelList())
}
uiState.value = UiState.Loading.LoadFromNetwork
try {
val recentVersions = api.getRecentAndroidVersions()
for (version in recentVersions) {
database.insert(version.mapToEntity())
}
uiState.value = UiState.Success(DataSource.NETWORK, recentVersions)
} catch (exception: Exception) {
uiState.value = UiState.Error(DataSource.NETWORK, "Something went wrong!")
}
}
}
fun clearDatabase() {
viewModelScope.launch {
database.clear()
}
}
}
enum class DataSource(val dataSourceName: String) {
DATABASE("Database"),
NETWORK("Network")
}