首页 > 解决方案 > 从方法内的 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();
        }

标签: javaandroid

解决方案


尝试这个

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
}
});

推荐阅读