Skip to content

Instantly share code, notes, and snippets.

@LloydBlv
Created March 13, 2024 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LloydBlv/cb5bffe333dc719d877dc58067be9f45 to your computer and use it in GitHub Desktop.
Save LloydBlv/cb5bffe333dc719d877dc58067be9f45 to your computer and use it in GitHub Desktop.
Avoid using init{} block in ViewModels
class SearchViewModel @Inject constructor(
private val searchUseCase: dagger.Lazy<SearchUseCase>,
private val wordsUseCase: GetWordsUseCase,
) : ViewModel() {
data class UiState(
val isLoading: Boolean = true,
val words: List<String> = emptyList()
)
val state: StateFlow<UiState> = flow {
emit(UiState(isLoading = true))
val words = wordsUseCase.invoke()
emit(UiState(isLoading = false, words = words))
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), UiState())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment