我正在使用协同程序将我的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)
}
//...
}
}
可解析是我为这个purpuse开发的自定义函数,这里是源代码:
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
}
我很快开发了可解析的功能(请记住它's a quick draft) using lambdas and semaphores but i don'知道是否有任何预先存在的功能(我找不到)或者可以优化或有任何缺点/问题 .
谢谢 .
1 回答
看起来你正在尝试重新发明
suspendCoroutine
功能 . 我建议用suspendCoroutine
调用替换你的resolvable
函数来获得你正在寻找的那种功能:如果在
suspendCoroutine
块周围执行"extract function"重构并命名生成的挂起函数prompt
,那么您可以使用与JS非常相似的样式编写代码 .您也可以考虑使用
suspendCancellebleCoroutine
而不是普通suspendCoroutine
. 这样,您可以支持取消已启动的协程并安装处理程序以在取消对话时关闭对话框 .