Skip to content

Try a reactive approach to update state flow in ViewModels #25

@dmitriy-chernysh

Description

@dmitriy-chernysh
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 }
    }
}```

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions