0

我有两个这样的组合:

@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 事件在一个小吃店可见时出现,我想忽略该新事件)

如何将这样的事件从一个可组合发送到另一个?

4

1 回答 1

1

我创建了一个小例子。我希望它对你有帮助。在我的情况下,我通过单击按钮生成一个“事件”

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()
        }
    }
}
于 2021-11-09T15:40:58.883 回答