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 }
}
}```