【发布时间】:2022-06-27 22:28:20
【问题描述】:
下面的代码有几个可能的故障。例如,width 可以为 null,或者r 可以为 false。在所有情况下,我都应该返回 result.error() 或类似的东西。
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
if (call.method == "getPlatformVersion") {
result.success("Android ${android.os.Build.VERSION.RELEASE}")
} else if (call.method=="registerTexture") {
val entry: TextureRegistry.SurfaceTextureEntry = texture_registry.createSurfaceTexture();
val surfaceTexture = entry.surfaceTexture();
//TODO: return non-sucess when no width and height passed
val width: Int = call.argument("width")!!
val height: Int = call.argument("height")!!
surfaceTexture.setDefaultBufferSize(width, height)
val response = HashMap<String, Long>()
RendererPlugin.surfaceTextureMap.put(entry, surfaceTexture)
val r = RendererPlugin.registerSurfaceTextureNativeHandler(entry.id(), surfaceTexture)
if (!r) {
Log.d(LOG_TAG, "attention: failed result from registerSurfaceTextureNativeHandler")
}
response.put("textureId", entry.id())
result.success(response)
}
}
在 Rust 上,我会将所有这些都变成一个闭包,产生 Result<(), Error>,然后在 onMethodCall 中执行闭包,如果我遇到错误,我会返回一个错误。此外,闭包将充满以? 结尾的调用,因此它会自动返回具有转换为Error 的From<> 实现的错误。
如何在 Kotlin 中有效地做到这一点?有没有办法进行闭包并在此闭包中轻松返回成功或错误,然后根据此结果我调用result.sucess 或result.error?
【问题讨论】:
标签: kotlin