pref: 事件流扩展方法

This commit is contained in:
HuanCheng65 2023-03-12 14:11:11 +08:00
parent 239e6109df
commit 5ff4c37a09
No known key found for this signature in database
GPG Key ID: E9031EF91A805148
1 changed files with 23 additions and 0 deletions

View File

@ -56,6 +56,29 @@ fun <T : UiState, A> Flow<T>.collectPartialAsState(
}
}
@Composable
inline fun <reified Event : UiEvent> Flow<UiEvent>.onEvent(
noinline listener: suspend (Event) -> Unit
) {
val coroutineScope = rememberCoroutineScope()
DisposableEffect(key1 = listener, key2 = this) {
with(coroutineScope) {
val job = launch {
this@onEvent
.filterIsInstance<Event>()
.cancellable()
.collect {
launch {
listener(it)
}
}
}
onDispose { job.cancel() }
}
}
}
@Composable
inline fun <reified Event : UiEvent> BaseViewModel<*, *, *, *>.onEvent(
noinline listener: suspend (Event) -> Unit