什么是同步/异步操作?
好吧,同步等待任务完成。在这种情况下,您的代码将“自上而下”地执行。
异步在后台完成任务,并在任务完成时通知您。
如果要通过方法/函数从异步操作返回值,则可以在方法/函数中定义自己的回调,以便在这些值从这些操作返回时使用这些值。
以下是Java的方法
首先定义一个接口:
interface Callback {
void myResponseCallback(YourReturnType result);//whatever your return type is: string, integer, etc.
}
接下来,将方法签名更改为如下所示:
public void foo(final Callback callback) { // make your method, which was previously returning something, return void, and add in the new callback interface.
接下来,无论您以前想在哪里使用这些值,请添加以下行:
callback.myResponseCallback(yourResponseObject);
例如:
@Override
public void onSuccess(QuerySnapshot documentSnapshots) {
// create your object you want to return here
String bar = document.get("something").toString();
callback.myResponseCallback(bar);
})
现在,您之前调用的方法名为:foo
foo(new Callback() {
@Override
public void myResponseCallback(YourReturnType result) {
//here, this result parameter that comes through is your api call result to use, so use this result right here to do any operation you previously wanted to do.
}
});
}
你如何为Kotlin做到这一点?(作为一个基本的例子,你只关心一个结果)
首先将方法签名更改为如下所示的内容:
fun foo(callback:(YourReturnType) -> Unit) {
.....
然后,在异步操作的结果中:
firestore.collection("something")
.document("document").get()
.addOnSuccessListener {
val bar = it.get("something").toString()
callback(bar)
}
然后,您之前会将方法称为 ,现在执行以下操作:foo
foo() { result->
// here, this result parameter that comes through is
// whatever you passed to the callback in the code aboce,
// so use this result right here to do any operation
// you previously wanted to do.
}
// Be aware that code outside the callback here will run
// BEFORE the code above, and cannot rely on any data that may
// be set inside the callback.
如果你的方法以前采用了参数:foo
fun foo(value:SomeType, callback:(YourType) -> Unit)
您只需将其更改为:
foo(yourValueHere) { result ->
// here, this result parameter that comes through is
// whatever you passed to the callback in the code aboce,
// so use this result right here to do any operation
// you previously wanted to do.
}
这些解决方案演示如何创建方法/函数,以从通过使用回调执行的异步操作返回值。
但是,重要的是要了解,如果您不有兴趣为这些创建方法/函数:
@Override
public void onSuccess(SomeApiObjectType someApiResult) {
// here, this `onSuccess` callback provided by the api
// already has the data you're looking for (in this example,
// that data would be `someApiResult`).
// you can simply add all your relevant code which would
// be using this result inside this block here, this will
// include any manipulation of data, populating adapters, etc.
// this is the only place where you will have access to the
// data returned by the api call, assuming your api follows
// this pattern
})