'Jetpack compose and viewModels - Ignore last state value on first composition

How do i ignore the viewModel's last state on the first composition of a composable? The usecase is the following:

  1. User enters MyDumbComposable
  2. Clicks to add a song to a playlist
  3. When the action is successful, popBack

This is my viewModel

@HiltViewModel
class AddToPlaylistViewModel @Inject constructor(
    private val addToPlaylistUseCase: AddToPlaylistUseCase,
) : ViewModel() {

    private val _state = mutableStateOf<AddToPlaylistState>(AddToPlaylistState.Initial)

    val state: State<AddToPlaylistState> = _state

    operator fun invoke(
        params: AddToPlaylistParams
    ) {
        addToPlaylistUseCase(params)
            .flowOn(Dispatchers.IO)
            .onEach { _state.value = it }
            .launchIn(viewModelScope)
    }
}

This is MyDumbComposable

fun MyDumbComposable(
    addToPlaylistViewModel: AddToPlaylistViewModel = hiltViewModel(),
    song: Song,
    popBack: () -> Unit
) {
    if (addToPlaylistViewModel.state.value is AddToPlaylistState.Loaded) {
        LaunchedEffect(Unit) {
            popBack()
        }
    }

    fun onClick(playlist: PlaylistWithSongs) {
        addToPlaylistViewModel(
            AddToPlaylistParams(
                selected = Selected(listOf(song)),
                playlist = playlist.playlist
            )
        )
    }
 ///...

It works the first time and pops correctly. However, whenever the user returns to that composable, the AddToPlaylistViewModel is cached so the last value is still AddToPlaylistState.Loaded, meaning it'll pop the screen right away.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source