简体   繁体   English

在Android上取代Kotlin Coroutine的回调

[英]Replace callbacks by Kotlin Coroutine on Android

How can I replace my callbacks with coroutine? 如何用coroutine替换我的回调? It's possible? 这是可能的? I tried to replace my onclick event of adapter item using suspendCoroutine: 我尝试使用suspendCoroutine替换适配器项的onclick事件:

suspend fun waitForButtonClick() = suspendCoroutine<String> { continuation ->
    button.setOnClickListener {
        continuation.resume("My Data")
    }
}

And on activity: 在活动上:

GlobalScope.launch {
  val callbackResult = adapter.waitForButtonClick()
}

The problem is that I can call waitForButtonClick only one time, because resume can be executed only one time. 问题是我只能调用waitForButtonClick一次,因为resume只能执行一次。 How to replace the onClickCallback with Kotlin coroutine? 如何用Kotlin协同程序替换onClickCallback?

the problem is that calling setOnClickListener overwrites the old listener. 问题是调用setOnClickListener会覆盖旧的侦听器。

you can use something like this to collect the suspended functions: 你可以使用这样的东西收集暂停的功能:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    button.setOnClickListener(this::resumeSuspendedClickFunctions)
}

private val suspendedClickFunctions = LinkedList<View.OnClickListener>()

private fun resumeSuspendedClickFunctions(view: View){
    suspendedClickFunctions.forEach {
        it.onClick(view)
    }
    suspendedClickFunctions.clear()
}

suspend fun waitForButtonClick() = suspendCoroutine<String> { continuation ->
    val listener = View.OnClickListener {
        continuation.resume("My Data")
    }
    suspendedClickFunctions.add(listener)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM