Search module with Jetpack compose
- In the
Studentdata class the functioninterpretInputTextdefine as much pattern as you need for your custom search. - In
MainViewModel3 main stateFlow: searchInput, isSearching and students list, which are converted to compose state in MainActivity while collecting:collectAsState() studentslist depend onsearchInputand_studentsthat's why we usecombineoperator which will be triggred whenver one of those are changed.- The logic behind adding
.debounce(1000L)is to improve search performance when implementing search with a real remote API: it create a delay until next block is executed, meanwhile if thesearchInputchange value the previous call/emission (with previous value) is canceled and the new value will be used for search, and by doing this we reduce the API call. - In MainActivity to be able to get instance of MainViewModel like this:
val mainViewModel = viewModel<MainViewModel>()you need first to add the dependency:implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.6.2")
Note: there is no architecture followed here