From aa15e65a7764348ddf745e013308727c25eb78b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Mlynari=C4=8D?= Date: Fri, 8 Mar 2024 10:30:32 +0100 Subject: [PATCH] Fix search flickering Change-Id: I6d17f5703186dbebcba4f931ab9692d4ab1e9f79 --- .../feature/search/SearchViewModel.kt | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/feature/search/src/main/kotlin/com/google/samples/apps/nowinandroid/feature/search/SearchViewModel.kt b/feature/search/src/main/kotlin/com/google/samples/apps/nowinandroid/feature/search/SearchViewModel.kt index 6dd93ceb6..7c05f81c5 100644 --- a/feature/search/src/main/kotlin/com/google/samples/apps/nowinandroid/feature/search/SearchViewModel.kt +++ b/feature/search/src/main/kotlin/com/google/samples/apps/nowinandroid/feature/search/SearchViewModel.kt @@ -26,11 +26,11 @@ import com.google.samples.apps.nowinandroid.core.data.repository.RecentSearchRep import com.google.samples.apps.nowinandroid.core.domain.GetRecentSearchQueriesUseCase import com.google.samples.apps.nowinandroid.core.domain.GetSearchContentsCountUseCase import com.google.samples.apps.nowinandroid.core.domain.GetSearchContentsUseCase -import com.google.samples.apps.nowinandroid.core.result.Result -import com.google.samples.apps.nowinandroid.core.result.asResult +import com.google.samples.apps.nowinandroid.core.model.data.UserSearchResult import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map @@ -61,18 +61,15 @@ class SearchViewModel @Inject constructor( flowOf(SearchResultUiState.EmptyQuery) } else { getSearchContentsUseCase(query) - .asResult() - .map { result -> - when (result) { - is Result.Success -> SearchResultUiState.Success( - topics = result.data.topics, - newsResources = result.data.newsResources, - ) - - is Result.Loading -> SearchResultUiState.Loading - is Result.Error -> SearchResultUiState.LoadFailed - } + // Not using .asResult() here, because it emits Loading state every + // time the user types a letter in the search box, which flickers the screen. + .map { data -> + SearchResultUiState.Success( + topics = data.topics, + newsResources = data.newsResources, + ) } + .catch { emit(SearchResultUiState.LoadFailed) } } } }