Created
September 24, 2022 17:02
-
-
Save SEAbdulbasit/53d837b9bb18aeb848bead0324152a79 to your computer and use it in GitHub Desktop.
Music Details View Model
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
@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