使用“记住”来存储取消协程作业的函数

问题描述 投票:0回答:1

如何记住 Jetpack Compose 中的函数?我希望

search
函数返回另一个函数,该函数将取消其两项作业,以便当用户再次点击
search
时,它不会启动另一个并行搜索,而是取消前一个:

这是

search
功能:

fun search(coroutineScope: CoroutineScope): () -> Unit {

        payments.clear()

        val channel = Channel<Payment>()

        val producer = coroutineScope.launch(Dispatchers.IO) {
            println("Query started.")
            fetchPayments(filter, channel)
            println("Query finished.")
        }
        val consumer = coroutineScope.launch {
            updatePayments(channel, payments)
            println("Updated: ${payments.size}")
        }
        return fun() {
            producer.cancel()
            consumer.cancel()
        }
    }

这个调用搜索,需要存储取消函数:

@Composable
fun Browser() {

    val coroutineScope = rememberCoroutineScope()
    val cancelSearch = remember {} // <-- What goes in here?

    Button(onClick = { 
            cancelSearch.value() // <-- this needs to cancel the previouis search (if any)
            cancelSearch = model.search(coroutineScope) // updates the cancellation function
        }, 
        modifier = Modifier.weight(1f)) {
            Text("Search")
        }
    )
}
kotlin android-jetpack-compose kotlin-coroutines desktop-application cancellation
1个回答
0
投票

这是一种保持函数处于状态的方法。

var cancelSearch by rememberSaveable { mutableStateOf<(() -> Unit)?>(null) }

Button(onClick = {
    cancelSearch?.invoke()
    cancelSearch = search(coroutineScope)
} 
© www.soinside.com 2019 - 2024. All rights reserved.