有什么(更好的)方法可以通过 `callbackFlow` 来组合桌面 `onClick` 吗?
Any(better) approach to pass compose desktop's `onClick` through `callbackFow`?
我想知道是否可以通过 onClik
[处理 onClick
] 通过 callbackFlow
正如我从 post 中看到的那样。
我很难实现,因为 onClick Callback
在参数内部,而且 Button
是函数,所以无法实现扩展函数
反正我试过
lateinit var buttonListener :Flow<Unit>
fun <T >offers(t: T) = callbackFlow {
offer(t)
awaitClose { null }
}
CoroutineScope(IO).launch {
if(::buttonListener.itInitalized){
buttonListener.collect {
println("it => Kotlin.Unit")
}
}
}
MaterialTheme {
Button(
onClick = {
println("buttonClicked")
buttonListener = offers(Unit)
} //...
) { /** designs */}
}
每次运行时只能调用 1 次
buttonClicked <--\
Kotlin.Unit => Kotlin.Unit <--/\__first click
buttonClicked
buttonClicked
buttonClicked
但期待
buttonClicked
Kotlin.Unit => Kotlin.Unit
buttonClicked
Kotlin.Unit => Kotlin.Unit
buttonClicked
Kotlin.Unit => Kotlin.Unit
您可以使用协程 Channel
而不是 Flow
来接收来自协程外部的事件。然后使用 consumeAsFlow()
方法将其转换为 Flow
。
现在可以在此 Flow
上调用像 collect
这样的流运算符了。
它可以接收来自按钮可组合项的多个 onClick
事件。
var buttonListener = Channel<Unit>()
CoroutineScope(Dispatchers.IO).launch {
buttonListener.consumeAsFlow().collect {
Log.d(TAG, "onCreate: $it => Kotlin.Unit")
}
}
MaterialTheme {
Button(
onClick = {
Log.d(TAG, "onCreate: buttonClicked")
buttonListener.offer(Unit)
}
){
Text(text = "Button")
}
}
我想知道是否可以通过 onClik
[处理 onClick
] 通过 callbackFlow
正如我从 onClick Callback
在参数内部,而且 Button
是函数,所以无法实现扩展函数
反正我试过
lateinit var buttonListener :Flow<Unit>
fun <T >offers(t: T) = callbackFlow {
offer(t)
awaitClose { null }
}
CoroutineScope(IO).launch {
if(::buttonListener.itInitalized){
buttonListener.collect {
println("it => Kotlin.Unit")
}
}
}
MaterialTheme {
Button(
onClick = {
println("buttonClicked")
buttonListener = offers(Unit)
} //...
) { /** designs */}
}
每次运行时只能调用 1 次
buttonClicked <--\
Kotlin.Unit => Kotlin.Unit <--/\__first click
buttonClicked
buttonClicked
buttonClicked
但期待
buttonClicked
Kotlin.Unit => Kotlin.Unit
buttonClicked
Kotlin.Unit => Kotlin.Unit
buttonClicked
Kotlin.Unit => Kotlin.Unit
您可以使用协程 Channel
而不是 Flow
来接收来自协程外部的事件。然后使用 consumeAsFlow()
方法将其转换为 Flow
。
现在可以在此 Flow
上调用像 collect
这样的流运算符了。
它可以接收来自按钮可组合项的多个 onClick
事件。
var buttonListener = Channel<Unit>()
CoroutineScope(Dispatchers.IO).launch {
buttonListener.consumeAsFlow().collect {
Log.d(TAG, "onCreate: $it => Kotlin.Unit")
}
}
MaterialTheme {
Button(
onClick = {
Log.d(TAG, "onCreate: buttonClicked")
buttonListener.offer(Unit)
}
){
Text(text = "Button")
}
}