java - 从方法内的 lambda 返回值
问题描述
我完全迷失在这里。我有这样的方法
String foo(String param) {
seechOutput(params, () -> {
// Callback after the task is performed!
// Speech output task.
speechInput(params, (result) -> {
// Some calculations.
// Now return result to the caller function of foo.
});
});
}
我在 lambda 之外尝试了 while() 循环,但没有奏效。
如何返回值?
有没有更好的设计方法?
编辑:这是原始代码。
String getNumberFromName(String name) {
AtomicReference<String> finalResult = new AtomicReference<>("");
int i = 1;
StringBuilder toSpeak = new StringBuilder("There are multiple contacts, Which one you wanted to call? ");
for (String s : hs.keySet()) {
toSpeak.append(i).append(". ").append(s).append(", ");
++i;
}
System.out.println(toSpeak);
audioOutput.speak(String.valueOf(toSpeak), TextToSpeech.QUEUE_FLUSH, "multiple1", () -> {
runOnUiThread(() -> {
mSpeechInput.startListening((str) -> {
finalResult.set(str);
});
});
});
return finalResult.get();
}
解决方案
尝试这个
String foo(String param) {
String finalResult = "";
seechOutput(params, () -> {
// Callback after the task is performed!
// Speech output task.
speechInput(params, (result) -> {
// Some calculations.
// Now return result to the caller function of foo.
finalResult = result;
});
});
return finalResult;
}
如果您的功能是同步的,那么这将完美地工作。如果您正在执行一些异步操作,那么
finalResult
将是空的。
如果它是异步的,请这样做
interface AsyncCallback {
void catchResult(String result)
}
编辑您的方法,例如
foo(String param,AsyncCallback callback) {
// your code here
speechInput(params, (result) -> {
//here use the method
callback.catchResult(result)
});
}
像这样使用它
foo("params", new AsyncCallback() {
@Override
public void catchResult(String number) {
// result here
}
});
推荐阅读
- reactjs - 如何使用 react 和 typescript 根据所选选项列出数据?
- google-drive-api - 如何在 Mac 上配置谷歌备份和同步以将照片上传到谷歌云?
- pyqt - 为什么中央小部件(QWidget)从另一个文件导入时没有正确调整大小?
- sql - 使用多个表的 MS Access SQL UPDATE
- java - Java.util.NoSuchElementException 类分配错误
- c - 在 Windows 上以编程方式对文件进行碎片整理
- tablesorter - 如何在 textSorter 中对隐藏或数据属性值进行排序
- splunk - 如何在 Splunk 的案例中访问数组值?
- c++ - 编译时的不变检查
- javascript - 使用 Apps 脚本在 Google Docs 中的选定表上追加新行