android - How to prevent ModalBottomSheet content from loading only once in Jetpack Compose? - Stack Overflow

admin2025-04-19  0

On one screen I'm using a ModalBottomSheet to play text to audio using TTS.

I'm delaying getting the text to read until the ModalBottomSheet is displayed.

The code works, but if I hide the ModalBottomSheet and click the button again to display it, the part of the code that fetches the text to read is executed again.

How can I fetch the content to read only once and only change it when the content changes?

    if (showBottomSheet) {
        ModalBottomSheet(
            onDismissRequest = {
                showBottomSheet = false
            },
            sheetState = sheetState,

            content = {
                analyticsHelper.logUniversalisTtsEvent(universalisResource.title)
                val read = universalisBodyForRead(universalis, typusId, userData)
                viewModelTts.loadData(read.text)
                ScreenTtsPlayer(viewModelTts)
            },
        ) 
    }

I've tried LaunchedEffect, but it doesn't work for me.

On one screen I'm using a ModalBottomSheet to play text to audio using TTS.

I'm delaying getting the text to read until the ModalBottomSheet is displayed.

The code works, but if I hide the ModalBottomSheet and click the button again to display it, the part of the code that fetches the text to read is executed again.

How can I fetch the content to read only once and only change it when the content changes?

    if (showBottomSheet) {
        ModalBottomSheet(
            onDismissRequest = {
                showBottomSheet = false
            },
            sheetState = sheetState,

            content = {
                analyticsHelper.logUniversalisTtsEvent(universalisResource.title)
                val read = universalisBodyForRead(universalis, typusId, userData)
                viewModelTts.loadData(read.text)
                ScreenTtsPlayer(viewModelTts)
            },
        ) 
    }

I've tried LaunchedEffect, but it doesn't work for me.

Share Improve this question asked Mar 5 at 23:08 A. CedanoA. Cedano 1,00117 silver badges50 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

the read and loadData calls are side effects and it will be triggered every time the composable recomposed not only when you dismiss and reopen the dialog . why LaunchedEffect didn't help you ? just with launchedEffect you told the compose compiler you need to execute this one time at the first composition so this will never execute again with every recomposition but when you dismis and reopen the dialog this is a new composition so it will execute again . so ? the best option for me is that make viewModel for this dialog and in the init of this dialog call your methods .... what if one of them you need to call again and again with every dialog open ? just use the launchedEffect(Unit)

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745003291a279362.html

最新回复(0)