Created
August 4, 2025 12:52
-
-
Save mahdiPourkazemi/a9abb82df0ea05a524b64eeb63e3cb5c to your computer and use it in GitHub Desktop.
Search With Flow Powered
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SearchViewModel : ViewModel() { | |
private val _searchQuery = MutableSharedFlow<String>() | |
val searchResults: StateFlow<UiState<List<SearchResult>>> = _searchQuery | |
.debounce(300) // صبر میکنه تا کاربر تایپ کردن رو تموم کنه | |
.filter { it.length >= 3 } // حداقل 3 کاراکتر | |
.flatMapLatest { query -> | |
if (query.isEmpty()) { | |
flowOf(UiState.Success(emptyList())) | |
} else { | |
searchRepository.search(query) | |
.map<List<SearchResult>, UiState<List<SearchResult>>> { | |
UiState.Success(it) | |
} | |
.onStart { emit(UiState.Loading) } | |
.catch { emit(UiState.Error(it, "خطا در جستجو")) } | |
} | |
} | |
.stateIn( | |
viewModelScope, | |
SharingStarted.WhileSubscribed(5000), | |
UiState.Success(emptyList()) | |
) | |
fun search(query: String) { | |
_searchQuery.tryEmit(query) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment