如何在 Android Kotlin 中包装异步 Java 库?
How to wrap an asynchronous Java lib in Android Kotlin?
我想在我的 Kotlin Android 应用程序中使用 Java 库,但我对 Kotlin 比较陌生,需要一些建议。图书馆基本上是这样的:
public interface Listener{
void onResult(Result res)
}
public class Client{
public Client(){}
public void setListener(Listener l){}
public void start(){} // Starts Thread(s) (so it's non-blocking), does some server calls, computes result, calls listener.onResult(res) after computation is finished.
public void cancel(){}
}
是的,我知道,我可以直接调用函数并像 java 那样使用它,但这是 Kotlin 的方式吗?
我读过,做一个类似的任务(使用一个异步函数,它接受一个回调参数)将通过将它包装在一个 coroutine/suspend 函数结构中来完成。
但我不知道如何针对我的问题(?)调整它,还是错误的方法?
如果你想把它做成一个很好的简单的 Kotlin 挂起函数,它会是这样的:
suspend fun doTheThing() : Result {
val c = Client()
try {
//suspend until the listener fires or we're cancelled
return suspendCancellableCoroutine {
cont ->
c.setListener {
result -> cont.resume(result)
}
c.start()
}
} catch (e: Exception) {
// If someone cancels the parent job, our job will complete exceptionally
// before the client is done. Cancel the client since we don't need it
// anymore
c.cancel()
throw e
}
}
我没有在您的界面中看到客户端指示失败的方式。如果那是 Result
的一部分,那么您可能希望将其转换为侦听器中的异常
我想在我的 Kotlin Android 应用程序中使用 Java 库,但我对 Kotlin 比较陌生,需要一些建议。图书馆基本上是这样的:
public interface Listener{
void onResult(Result res)
}
public class Client{
public Client(){}
public void setListener(Listener l){}
public void start(){} // Starts Thread(s) (so it's non-blocking), does some server calls, computes result, calls listener.onResult(res) after computation is finished.
public void cancel(){}
}
是的,我知道,我可以直接调用函数并像 java 那样使用它,但这是 Kotlin 的方式吗? 我读过,做一个类似的任务(使用一个异步函数,它接受一个回调参数)将通过将它包装在一个 coroutine/suspend 函数结构中来完成。 但我不知道如何针对我的问题(?)调整它,还是错误的方法?
如果你想把它做成一个很好的简单的 Kotlin 挂起函数,它会是这样的:
suspend fun doTheThing() : Result {
val c = Client()
try {
//suspend until the listener fires or we're cancelled
return suspendCancellableCoroutine {
cont ->
c.setListener {
result -> cont.resume(result)
}
c.start()
}
} catch (e: Exception) {
// If someone cancels the parent job, our job will complete exceptionally
// before the client is done. Cancel the client since we don't need it
// anymore
c.cancel()
throw e
}
}
我没有在您的界面中看到客户端指示失败的方式。如果那是 Result
的一部分,那么您可能希望将其转换为侦听器中的异常