Created
March 13, 2024 13:32
-
-
Save LloydBlv/30a69daeffc3784d88e023cf43bccd11 to your computer and use it in GitHub Desktop.
Better implementation of ViewModel, eliminating init{} block
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: dagger.Lazy<SearchUseCase>, | |
) : ViewModel() { | |
private val searchQuery = MutableStateFlow("") | |
val uiState: LiveData<SearchUiState> = searchQuery | |
.debounce(DEBOUNCE_TIME_IN_MILLIS) | |
.asLiveData() | |
.switchMap(::createUiState) | |
private fun createUiState(query: @JvmSuppressWildcards String) = liveData { | |
Timber.d("collectLatest(), query:[%s]", query) | |
if (query.isEmpty()) { | |
emit(SearchUiState.Idle) | |
return@liveData | |
} | |
try { | |
emit(SearchUiState.Loading) | |
val photos = searchUseCase.get().invoke(query) | |
if (photos.isEmpty()) { | |
emit(SearchUiState.EmptyResult) | |
} else { | |
emit(SearchUiState.Success(photos)) | |
} | |
} catch (e: Exception) { | |
emit(SearchUiState.Error(e)) | |
} | |
} | |
fun onQueryChanged(query: String?) { | |
query ?: return | |
searchQuery.value = query | |
} | |
sealed class SearchUiState { | |
data object Loading : SearchUiState() | |
data object Idle : SearchUiState() | |
data class Success(val photos: List<FlickrPhoto>) : SearchUiState() | |
data 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