Last active
June 27, 2023 13:58
-
-
Save tdcolvin/dd453f6ccd79fa24b4c15b6ea0176b75 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
@HiltViewModel | |
class AddEditPlanetViewModel @Inject constructor( | |
savedStateHandle: SavedStateHandle, | |
private val planetsRepository: PlanetsRepository | |
): ViewModel() { | |
private val planetId: String? = savedStateHandle[PlanetsDestinationsArgs.PLANET_ID_ARG] | |
private val _uiState = MutableStateFlow(AddEditPlanetUiState()) | |
val uiState: StateFlow<AddEditPlanetUiState> = _uiState.asStateFlow() | |
init { | |
if (planetId != null) { | |
loadPlanet(planetId) | |
} | |
} | |
private fun loadPlanet(planetId: String) { | |
_uiState.update { it.copy(isLoading = true) } | |
viewModelScope.launch { | |
val result = planetsRepository.getPlanetFlow(planetId).first() | |
if (result !is WorkResult.Success || result.data == null) { | |
_uiState.update { it.copy(isLoading = false) } | |
} | |
else { | |
val planet = result.data | |
_uiState.update { | |
it.copy( | |
isLoading = false, | |
planetName = planet.name, | |
planetDistanceLy = planet.distanceLy, | |
planetDiscovered = planet.discovered | |
) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment