Skip to content

Instantly share code, notes, and snippets.

@skydoves
Last active September 19, 2024 16:43
Show Gist options
  • Save skydoves/1c82da0a713171fbfe8d935837512e8a to your computer and use it in GitHub Desktop.
Save skydoves/1c82da0a713171fbfe8d935837512e8a to your computer and use it in GitHub Desktop.
DetailsViewModel
// https://github.com/skydoves/pokedex-compose
@HiltViewModel
class DetailsViewModel @Inject constructor(
detailsRepository: DetailsRepository,
savedStateHandle: SavedStateHandle,
) : ViewModel() {
val pokemon = savedStateHandle.getStateFlow<Pokemon?>("pokemon", null)
val pokemonInfo: StateFlow<PokemonInfo?> =
pokemon.filterNotNull().flatMapLatest { pokemon ->
detailsRepository.fetchPokemonInfo(
name = pokemon.nameField.replaceFirstChar { it.lowercase() },
onComplete = { uiState.tryEmit(key, DetailsUiState.Idle) },
onError = { uiState.tryEmit(key, DetailsUiState.Error(it)) },
)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = null,
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment