YASAN

    YASAN

    10 months ago
    I am having some confusion on how I should handle life cycles on Compose to achieve the behavior I want. I have a traditional
    View
    on my Composable which I need to
    init
    to show. The
    init
    is a heavy process so I really want to avoid doing it when its not needed.
    I want to dispose/release it when the screen is destroyed but not when its paused/stopped.
    Currently it is released/disposed whenever the screen changes no matter if the previous screen is still in the backstack or not.
    I have this to dispose/create it:
    DisposableEffect(key1 = youTubePlayerViewModel) {
    
        youTubePlayerViewMutable.value = YouTubePlayerView(context)
    
        onDispose {
    
            youTubePlayerViewMutable.value?.release()
    
        }
    }
    I also have this code to call the
    init
    function which is outside of onDispose:
    LaunchedEffect(video.id) {
        youTubePlayerViewMutable.value?.let {
            it.initialize()
        }
    }
    Alex

    Alex

    10 months ago
    Why not use an
    AndroidView
    ?
    YASAN

    YASAN

    10 months ago
    Based on my logs, it looks like
    onDispose
    is called even when I am navigating to a new screen and the screen is on backstack
    @Alex I am. This is not my full code. I am just initing it on other places.
    I need to use
    AndroidView
    to show a view and there isnt any other options afaik. The question is how to avoid reinitializing the view when its unneeded. My screen is basically being resumed but my view is being reinitialized which is an unwanted behavior for me.
    Alex

    Alex

    10 months ago
    you could initialize it in the factory and update it in the update lambda. If you need a longer living service behind it a viewmodel or repo is an appropiate place. LaunchedEffect is disposed when the composable leaves the composition or (in your case) when the video.id changes. The same goes for DisposableEffect (and youTubePlayerViewModel in your case) So either the composable left the composition or your keys changed. If you need something to live longer than the composition, it should reside in the viewmodel or a service. You could check if your keys changed without you intending that they do
    YASAN

    YASAN

    10 months ago
    I will try moving it to the factory and will check if I can change the keys to something better. I guess the main idea is to move stuff out of the LaunchedEffect as it is called on recomposition. I did try moving it to the ViewModel before but it could cause crashes when the orientation had changed but I guess I can re init it when the orientation changes. I have different layouts for portrait and landscape mode of this screen. Thanks ill try these out. Lifecycles are a bit confusing on Compose for me yet.