前言
Jetpack Compose并没有提供组件之间的事件交互,这里我们可以使用flow自定义一个EventBus来实现。
工具类
1 | import androidx.lifecycle.Lifecycle |
定义事件
1 | // 普通事件 |
订阅事件
1 | lifecycleScope.launch { |
Compose组件内使用
1 | val lifecycleOwner = LocalLifecycleOwner.current |
带参数的
1 | val lifecycleOwner = LocalLifecycleOwner.current |
接收到事件后记得移除事件
1 | ZFlowEventBus.removeEvent(it) |
发送事件
1 | // 在 ViewModel 或协程中发送普通事件 |
Composable 组件中
1 | val coroutineScope = rememberCoroutineScope() |
移除事件
1 | // 在需要时移除粘性事件(如退出登录) |