我目前有一个回调函数,它不会同步返回值,而是需要进行一些异步工作,然后返回结果。我一直在研究如何做到这一点,但我还没有弄清楚。到目前为止,我已经达到了这个目标,但由于我需要在foo方法中返回一个值,所以首先它返回“something”,然后再返回调用someMethod()的结果。
我是否能够实现我想要的功能?
class CustomClass() :
SomeClass.SomeInterface {
override fun foo(p0: SomeType): String {
val result = "something"
MainScope().launch {
withContext(Dispatchers.IO) {
result = someMethod()
}
}
return result
}
suspend fun someMethod(): String =
suspendCancellableCoroutine { cancelableContinuation ->
//TODO: register some listener that will end up calling
cancelableContinuation.resume("some_value", {})
}
提前致谢!
Flow
。 - momvart