0

I wrote my app with Jetpack Compose and navigation component. Also using MVVM. I have a single activity with five screen. when user enter to list screen1 from home screen, maybe play a sound. I want to stop and release Media Player when user press back and leave screen. because of Navigating with Compose, there is no fragments , I have just composable screen associate with view model. now I wondering where should I release my resources like Media Player? because Media Player is UI thing, my view model does not know anything about it.

My solouion: using DisposableEffect so on Lifecycle.Event.ON_STOP , I stop media player

Fereshteh Naji
  • 104
  • 1
  • 11

2 Answers2

1

As long as you have a single activity, always override the onDestroy() method of the activity lifecycle to dispose of everything when your app is killed (either by the user or by the system to save resources).

override fun onDestroy(){
 mediaPlayer.release()
 super.onDestroy()
}

Now, your ideology of "viewmodel knows nothing of the UI" is lethal. Please take the State in Compose codelab paying special attention to the part explaining state-hoisting.

  • I need to know about lifecycle of screen to release media player resource when user leave screen. so I resolved the problem with DisposableEffect from here: https://developer.android.com/jetpack/compose/side-effects And you right about ondestroy() but I create media player in different screen and my activity contain five screen so that wasn't a good idea. – Fereshteh Naji Jan 01 '22 at 06:57
  • Thank you about introduce state code lab, I will take that. – Fereshteh Naji Jan 01 '22 at 07:00
  • Well, you should consider adding that info (five screens and separate activities) so that people can answer specifically to your use-case. Anyway, I'm glad your issue is resolved! –  Jan 01 '22 at 16:22
0

if I get right you have to create a funtion and use androidview to wrap the mediaplayer component, but if what you want is to load a media file you have to place it in res/raw and access throught context, to get the context in a compose function you have to use LocalContext.current

https://developer.android.com/jetpack/compose/interop/interop-apis?hl=en-419

lau
  • 351
  • 2
  • 7
  • Thank you, but no you didn't get right. I need to know about lifecycle of screen to release media player resource when user leave screen. so I resolved the problem with DisposableEffect from here: https://developer.android.com/jetpack/compose/side-effects – Fereshteh Naji Jan 01 '22 at 06:53