How can I correctly implement SearchView using the ROOM library?

45 Views Asked by At

I'm looking to implement a SearchView feature in an app that utilizes the ROOM library. During my online research, I noticed that many examples and tutorials follow a pattern similar to the one below:

override fun onQueryTextChange(newText: String?): Boolean {
        if (newText != null) {
            mViewModel.searchAllDatabase(newText).observe(viewLifecycleOwner){
                ...
            }
        }
        return true
    }

But with this approach, a new observer is created each time a user enters a new letter and the onQueryTextChange method is triggered which may cause memory leaks i guess. What is the right way to do this?

1

There are 1 best solutions below

0
TheLibrarian On BEST ANSWER

First of all, you should start observing outside/before callbacks from the edit text - then it should be fine but...

The thing you are trying to do is usually done via streams/reactive constructs.

So rather than calling calling database in each change - have something listen to the changes of the search bar and let others listen to it.

private val query: MutableStateFlow<String> = MutableStateFlow("")

val searchAllDatabaseData: StateFlow<List<Item> = query.map { newQuery -> searchAllDatabase(newQuery)}

fun updateSearchQuery(query: String) {
    query.value = query
}