Код: Выделить всё
data class RecordsAppUiState(
val records : Flow,
val searchValue : String,
val category: Category = Category.ALL,
)
class RecordAppViewModel(var context: Context) : ViewModel() {
private var repository: LocalRecordsRepository =
LocalKitsRepository(RecordAppDatabase.getDatabase(context).recordDao())
private var recordsInDatabase = repository.getAllRecordsStream()
private var currentCategory = Category.ALL
private val _uiState: MutableStateFlow =
MutableStateFlow(
RecordsAppUiState(
records = recordsInDatabase,
searchValue = "",
)
)
val uiState = _uiState.asStateFlow()
fun onSearchValueChanged(newSearchValue: String) {
_uiState.value = _uiState.value.copy(
searchValue = newSearchValue,
records = recordsInDatabase.map { records ->
records.filter { record ->
(record.name.contains(newSearchValue, ignoreCase = true))
}
},
category = currentCategory,
)
}
// Adds the record to the wishlist
fun addRecordToUserWishlist(record: Record) {
record.IsInWishlist = !record.IsInWishlist
viewModelScope.launch(Dispatchers.IO) {
repository.updateRecord(record)
}
_uiState.value = _uiState.value.copy(
records =
recordsInDatabase.map { listRecords ->
listRecords.map { oldRecord ->
if (oldRecord.uid == record.uid) oldRecord.copy(
IsInWishlist = record.IsInWishlist,
) else oldRecord
}
},
)
}
}
Вот составной элемент, где я нажимаю значок:
Код: Выделить всё
@Composable
fun RecordAppCard(
record: Record,
addWishlistClicked: (Record) -> Unit,
) {
Card {
Text(
text = record.name,
)
Row {
IconButton(onClick = {
addWishlistClicked(record) // Calls addRecordToUserWishlist from viewModel above
}) {
Icon(
imageVector = if (record.IsInWishlist) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
contentDescription = "wishlist",
)
}
}
}
}
Код: Выделить всё
@Composable
fun RecordAppsMainScreen(
modifier: Modifier = Modifier,
viewModel: RecordAppViewModel = viewModel(),
) {
val uiState = viewModel.uiState.collectAsStateWithLifecycle()
val flowRecords = uiState.value.records
val listRecords = flowRecords.collectAsState(initial = emptyList()).value
LazyColumn(
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
item {
RecordAppSearchBar(
searchValue = uiState.value.searchValue,
onSearchChange = { viewModel.onSearchValueChanged(it) },
)
}
items(listRecords) { record ->
RecordAppCard(
record = record,
addWishlistClicked = { viewModel.addRecordToUserWishlist(record) },
)
}
}
}
Код: Выделить всё
var inWishlist by remember { mutableStateOf(kit.IsInWishlist) }Подробнее здесь: https://stackoverflow.com/questions/797 ... e-ui-state
Мобильная версия