-
Notifications
You must be signed in to change notification settings - Fork 22
Using room in coroutines
Devrath edited this page Jun 15, 2021
·
1 revision
- This example stores the response data of each network request in a Room database.
- This is essential for any "offline-first" app.
- If the View requests data, the ViewModel first checks if there is data available in the database.
- If so, this data is returned before performing a network request to get fresh data.
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")
}