Skip to content

Instantly share code, notes, and snippets.

@LloydBlv
Last active June 7, 2024 06:08
Show Gist options
  • Save LloydBlv/ad10d75faae83ff9f0de1f7523ee873b to your computer and use it in GitHub Desktop.
Save LloydBlv/ad10d75faae83ff9f0de1f7523ee873b to your computer and use it in GitHub Desktop.
class SearchViewModel @Inject constructor(private val searchRepo: SearchRepository): ViewModel() {
private val _searchQuery = MutableStateFlow("")
val searchResults: StateFlow<List<SearchResult>> = _searchQuery
.debounce(300) // Add a debounce to limit requests
.filter(String::isNotEmpty) // Ignore empty queries
.flatMapLatest(searchRepository::search)
.stateIn(viewModelScope, SharingStarted.Lazily, emptyList())
fun setSearchQuery(query: String) {
_searchQuery.update { query }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment