Created
March 13, 2024 13:30
-
-
Save LloydBlv/5e4b4381b6a08c3ef2c8d2f258bf96ee to your computer and use it in GitHub Desktop.
Bad implementation of ViewModel
This file contains 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 @Inject constructor( | |
private val searchUseCase: SearchUseCase, | |
@IoDispatcher val ioDispatcher: CoroutineDispatcher | |
) : ViewModel() { | |
private val searchQuery = MutableStateFlow("") | |
private val _uiState = MutableLiveData<SearchUiState>() | |
val uiState = _uiState | |
init { | |
viewModelScope.launch { | |
searchQuery.debounce(DEBOUNCE_TIME_IN_MILLIS) | |
.collectLatest { query -> | |
Timber.d("collectLatest(), query:[%s]", query) | |
if (query.isEmpty()) { | |
_uiState.value = SearchUiState.Idle | |
return@collectLatest | |
} | |
try { | |
_uiState.value = SearchUiState.Loading | |
val photos = withContext(ioDispatcher){ | |
searchUseCase.invoke(query) | |
} | |
if (photos.isEmpty()) { | |
_uiState.value = SearchUiState.EmptyResult | |
} else { | |
_uiState.value = SearchUiState.Success(photos) | |
} | |
} catch (e: Exception) { | |
_uiState.value = SearchUiState.Error(e) | |
} | |
} | |
} | |
} | |
fun onQueryChanged(query: String?) { | |
query ?: return | |
searchQuery.value = query | |
} | |
sealed class SearchUiState { | |
object Loading : SearchUiState() | |
object Idle : SearchUiState() | |
data class Success(val photos: List<FlickrPhoto>) : SearchUiState() | |
object EmptyResult : SearchUiState() | |
data class Error(val exception: Throwable) : SearchUiState() | |
} | |
companion object { | |
private const val DEBOUNCE_TIME_IN_MILLIS = 300L | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment