如何将事件传递给可组合项?

How to pass events to Composables?

我有两个这样的可组合项:

@Composable
fun Composable1(viewModel: MyViewModel) {
    LaunchedEffect(Unit) {
        viewModel.eventsFlow.collect { event ->
            if(event is ShowSnackbar) {
                // Send this event to Composable2 to show snackbar
            }
        }
    }
    Composable2(...) // passing some data and lambdas
}

@Composable
fun Composable2(...) {
    val scaffoldState = rememberScaffoldState()

    // On receiving event, show a snackbar

    Scaffold(scaffoldState) {
        // Other stuff
    }
}

(如果另一个 ShowSnackbar 事件在一个小吃店可见时发生,我想忽略那个新事件)

如何将此类事件从一个可组合项发送到另一个?

我创建了一个小例子。我希望它能帮助你。在我的例子中,我通过单击按钮

生成了一个“事件”
class ComposeActivity5 : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ComposeTutorialTheme {
                Composable1()
            }
        }
    }
}

@Composable
fun Composable1() {
    val scaffoldState = rememberScaffoldState()
    var showHide by remember { mutableStateOf(false) }
    var pressCount by remember { mutableStateOf(0) }

    Scaffold(
        scaffoldState = scaffoldState,
        content = { innerPadding ->
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier
                    .padding(innerPadding)
                    .fillMaxSize()
            ) {
                Button(onClick = {
                    pressCount++
                    showHide = true

                }) {
                    Text(text = "Test")
                }
                Composable2(scaffoldState, showHide, pressCount) {
                    showHide = false
                }
            }
        }
    )
}

@Composable
fun Composable2(
    scaffoldState: ScaffoldState,
    showHide: Boolean,
    pressCount: Int,
    onDismiss: () -> Unit
) {
    val mostRecentOnDismiss by rememberUpdatedState(onDismiss)
    LaunchedEffect(scaffoldState, showHide) {
        if (showHide) {
            scaffoldState.snackbarHostState.showSnackbar(
                message = "We are ignore press button to show Snackbar. Total number of clicks $pressCount",
                actionLabel = "Close",
                duration = SnackbarDuration.Short,
            )
            mostRecentOnDismiss()
        }
    }
}