Код: Выделить всё
interface ItemDao {
@Query("SELECT * FROM item_table")
fun getItems(): Flow
@Update
fun updateItem(item: Item)
}
Код: Выделить всё
interface ItemRepository {
fun getItems(): Flow
fun updateItem(item: Item)
}
Код: Выделить всё
class ItemsViewModel @Inject constructor(
private val repo: ItemRepository
) : ViewModel() {
private val _result = MutableStateFlow(Result.Loading)
val result: StateFlow = _result
.onStart {
getItems()
}.stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5_000L),
Result.Loading
)
private fun getItems() = viewModelScope.launch {
try {
repo.getItems().collect { items ->
_result.value = Result.Success(items)
}
} catch (e: Exception) {
_result.value = Result.Error(e)
}
}
Код: Выделить всё
val result = viewModel.result.collectAsStateWithLifecycle().value
Scaffold(
topBar = {
//
},
content = {
when(result) {
is Result.Loading -> CircularProgressIndicator()
is Result.Success -> {
items(
items = result.items
) { item ->
Text(item.name)
}
}
is Result.Error -> print(result.e)
}
}
)
Подробнее здесь: https://stackoverflow.com/questions/790 ... te-in-room
Мобильная версия