I have a problem with Lazycolumn refreshing if data in sql database changes. The list is on flow and refresh works if i start searching. But I don't know how to call the change of the list again after clicking the button that saves new data to the database.
ViewModel:
var listaPozycje = mutableStateOf<List<MagazynPozycjeDB>>(listOf())
private val _searchText = MutableStateFlow("")
val searchText = _searchText.asStateFlow()
private val _isSearching = MutableStateFlow(true)
val isSearching = _isSearching.asStateFlow()
private val _pozycje = MutableStateFlow(listaPozycje)
val pozycje = searchText
.debounce(1000L)
.onEach { _isSearching.update { true } }
.combine(_pozycje) { text, pozycje ->
if(text.isBlank()) {
pozycje.value
} else {
delay(500L)
pozycje.value.filter {
doesMatchSearchQuery(text)
}
}
}
.onEach { _isSearching.update { false } }
.stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5000),
_pozycje.value.value
)
fun onSearchTextChange(text: String) {
_searchText.value = text
}
fun doesMatchSearchQuery(query: String): Boolean {
val matchingCombinations = listOf(
listaPozycje.value[0].Indeks,
listaPozycje.value[0].NazwaIndeksu
)
return matchingCombinations.any {
it.contains(query, ignoreCase = true)
}
}
fun selectPozycje() {
viewModelScope.launch(Dispatchers.IO) {
val listaDok = magazynPozycjeDao.getPozycje(idMagazyn)
listaPozycje.value = listaDok
}
}
fun updateIlosc(ilosc: String, idMagazynDokumentyPozycje: String) {
viewModelScope.launch(Dispatchers.IO){
magazynPozycjeDao.updateIlosc(ilosc, id)
}
}
Fragment:
val searchText by viewModel.searchText.collectAsState()
val pozycje by viewModel.pozycje.collectAsState()
val isSearching by viewModel.isSearching.collectAsState()
LaunchedEffect(key1 = Unit, block = {
lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.selectPozycje()
viewModel.selectWydania()
}
}
})
Row(
modifier
.padding(top = 3.dp)
.weight(1f)) {
if(isSearching) {
Box(modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator(
modifier = Modifier.align(Alignment.Center), color = veritum_red
)
}
} else {
LazyColumn(modifier.weight(1f)) {
if (pozycje.isNotEmpty()) {
itemsIndexed(pozycje) { index, it ->
Button:
Button(
onClick = {
viewModel.updateIlosc(ilosc, pozycje[clickIndex].id)
viewModel.selectPozycje()
I cause the list to reload via viemodel.selectitems but it doesn't change anything