我正在使用协程将我的Android代码从Java重构为Kotlin,但我没有找到一种简单的方法将基于回调的代码重写为挂起函数。
一个基本的例子是返回结果的警报弹出窗口,在Javascript中它可能是这样的:
let value = prompt("please insert a value")
console.log("Value:"+value)
我会将其翻译成 Kotlin,大致意思如下:
class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
//Standard activity initialization
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Actual code...
launch {
val value = resolvable<String>(UI) { success, error ->
//Build a simple popup prompt with AlertDialog
val input = EditText(this@MainActivity)
val builder = AlertDialog.Builder(this@MainActivity)
.setTitle("please insert a value")
.setView(input)
.setPositiveButton("Ok",{ dialog, id ->
success(input.text.toString())//This lambda returns the value
})
val dialog = builder.create()
dialog.show()
}
println("Value:"+ value)
}
//...
}
}
Resolvable是我为此目的开发的自定义函数,以下是源代码:
import kotlinx.coroutines.experimental.DefaultDispatcher
import kotlinx.coroutines.experimental.cancelAndJoin
import kotlinx.coroutines.experimental.launch
import java.util.concurrent.Semaphore
import kotlin.coroutines.experimental.CoroutineContext
suspend fun <T> resolvable(
context: CoroutineContext = DefaultDispatcher,
block: suspend (success:(T?)->Unit,error:(Throwable)->Unit) -> Unit
):T?{
var result:T? = null
var exception:Throwable? = null
val semaphore = Semaphore(0)
val job = launch(context){
block({r:T? -> {
result=r
semaphore.release()
}},{e:Throwable -> {
exception=e
semaphore.release()
}})
}
semaphore.acquire()
job.cancelAndJoin()
if(exception!=null)
throw exception!!
return result
}
我使用lambda和semaphore快速开发了一个可解决函数(请记住这是一份快速草稿),但我不知道是否存在任何现有的函数(我找不到)。此函数是否可以优化或存在任何缺点/问题也不确定。
谢谢。