I’m in stuck.
I have Realm database. In viewmodel I receive data as a flow. In Fragment collect it.
Problem is when i want to filter / pass a param to realm query – there is no changes.
Viewmodel code:
class StateAppModel : ViewModel() {
val savedBooks: StateFlow<List<RealmBook>> = repository.allBooksAsFlowable(SearchDiaryFilters(searchDiaryText.value))
.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
}
Database:
fun allBooksAsFlowable(searchDiaryFilters: SearchDiaryFilters? = null): Flow<List<RealmBook>> {
return realm.query<RealmBook>().sort("created", Sort.DESCENDING).asFlow().map { it.list }
}
Fragment:
lifecycleScope.launch {
viewModel.savedBooks.collect {
booksAdapter.submitData(it)
}
}
I dont’t understand how to pass filter string, e.g. on EditText text change.
Thanks in advance!
>Solution :
To pass a filter string to ur Realm query based on EditText text changes ,u can modify your ViewModel and Fragment code to react to these changes. Here’s how ucan do it:
enter code here
class StateAppModel : ViewModel() {
private val searchDiaryTextFlow = MutableStateFlow("")
val savedBooks: StateFlow<List<RealmBook>> = searchDiaryTextFlow.flatMapLatest { searchText ->
repository.allBooksAsFlowable(SearchDiaryFilters(searchText))
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
fun setSearchDiaryText(searchText: String) {
searchDiaryTextFlow.value = searchText
}
}
In this modified ViewModel code, we introduce a searchDiaryTextFlow which is a MutableStateFlow representing the search text. Then, we use flatMapLatest to transform the search text into the corresponding Flow of books based on the filter. Whenever the search text changes, it will trigger a new query to the repository.
Fragment code:
class YourFragment : Fragment() {
private val viewModel: StateAppModel by viewModels()
private lateinit var booksAdapter: YourBooksAdapter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Initialize views and adapter
val searchEditText: EditText = view.findViewById(R.id.searchEditText)
searchEditText.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
// Update search text in ViewModel when text changes
viewModel.setSearchDiaryText(s.toString())
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
// Not used
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
// Not used
}
})
lifecycleScope.launch {
viewModel.savedBooks.collect {
// Update adapter with filtered books
booksAdapter.submitData(it)
}
}
}
}
In the Fragment code, we see changes to savedBooks and update the adapter accordingly. also We listen for changes in the search EditText and update the ViewModel’s search text accordingly using setSearchDiaryText.