Skip to content

Instantly share code, notes, and snippets.

@SEAbdulbasit
Created September 25, 2022 10:13
Show Gist options
  • Save SEAbdulbasit/5fc60a098f169af839ee50ab02b40502 to your computer and use it in GitHub Desktop.
Save SEAbdulbasit/5fc60a098f169af839ee50ab02b40502 to your computer and use it in GitHub Desktop.
@HiltViewModel
class MusicDetailViewModel @Inject constructor(
private val savedStateHandle: SavedStateHandle, private val repository: MusicRepository
) : ViewModel() {
val state: StateFlow<MusicDetailScreenState>
init {
val musicDetails = savedStateHandle.getStateFlow<Long>(MUSIC_ID, -1).filter { it != -1L }
.flatMapLatest { getMusicDetails(it) }
state = musicDetails.map { music ->
MusicDetailScreenState(
uiMModel = music
)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(stopTimeoutMillis = 5000),
initialValue = MusicDetailScreenState()
)
}
private suspend fun getMusicDetails(musicId: Long): Flow<MusicUiModel> {
return repository.getMusic(musicId).map {
MusicUiModel(
trackId = it.trackId,
musicTitle = it.musicTitle,
albumName = it.albumName,
artisName = it.artisName,
imageUrl = it.imageUrl.replace("100", "460"),
previewUrl = it.previewUrl
)
}.flowOn(Dispatchers.IO)
}
override fun onCleared() {
savedStateHandle[MUSIC_ID] = state.value.uiMModel.trackId
viewModelScope.cancel()
super.onCleared()
}
}
const val MUSIC_ID = "music_id"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment