Код: Выделить всё
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() {
val itemsResultFlow = flow {
repo.getItems().collect { items ->
try {
emit(Result.Success(items))
} catch (e: Exception) {
emit(Result.Failure(e))
}
}
}
var updateItemResult by mutableStateOf(Result.Loading)
private set
fun updateItem(item: Item) = viewModelScope.launch {
updateItemResult = try {
Result.Success(repo.updateItem(item))
} catch (e: Exception) {
Result.Failure(e)
}
}
}
Код: Выделить всё
val itemsResponse by viewModel.itemsResultFlow.collectAsStateWithLifecycle(Result.Loading)
Scaffold(
topBar = {
//
},
content = {
when(val itemsResponse = itemsResponse) {
is Result.Loading -> CircularProgressIndicator()
is Result.Success -> {
items(
items = itemsResponse.data
) { item ->
Text(item.name)
}
}
is Result.Error -> print(result.e)
}
}
)
Код: Выделить всё
private var _items = MutableStateFlow(Result.Loading)
val items: StateFlow = _items.asStateFlow()
init {
viewModelScope.launch {
repo.getItems().collect { items ->
try {
_items.value = Response.Success(items)
} catch (e: Exception) {
_items.value = Response.Failure(e)
}
}
}
}
Код: Выделить всё
val itemsResponse by viewModel.items.collectAsState()
Подробнее здесь: https://stackoverflow.com/questions/791 ... -an-update
Мобильная версия