使用CompletableFuture进行回调 [英] Callback with CompletableFuture

查看:413
本文介绍了使用CompletableFuture进行回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一些字符串创建一个非常简单的回调。 IDE的代码意义是对特殊的未经检查的调用抱怨。任何人都可以给我一个解决方案吗?最后的想法是包装网络呼叫,以便返回承诺的结果,我可以根据需要添加其他功能。

I'm trying to create a really simple callback using some Strings. The IDE's code sense is is moaning about an unchecked call to exceptionally. Can anyone give me a fix for this? The idea in the end is to wrap a network call so that the promised result is returned and I can tack on additional functions as needed.

import java.util.concurrent.*;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class FuturesTest {

    public static void main(String[] args) throws Exception {
        new FuturesTest().go();
    }

    private void go() throws ExecutionException, InterruptedException {
        CompletableFuture.supplyAsync(new MakesANetworkCall())
                .whenComplete(new BiConsumer<String, String>() {
                    @Override
                    public void accept(String result, String s) {
                        System.out.println(result.toString());
                    }
                })
                .exceptionally(new Function<Exception, Exception>() {
                                   @Override
                                   public Exception apply(Exception e) {
                                       e.printStackTrace();
                                       return e;
                                   }
                               }
                ).thenApplyAsync(new Function<String, String>() {
                    @Override
                    public String apply(String o) {
                        System.out.println("Last action of all!");
                        return null;
                    }
                });

        System.out.println("Main thread will sleep");
        Thread.sleep(2500);
        System.out.println("Program over");
    }

    class MakesANetworkCall implements Supplier {

        @Override
        public String get() {
            try {
                System.out.println("Ground control to Major Tom");
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            int i = 2/0;
            return new String("Major Tom reporting!");
        }
    }
}


推荐答案

首先,您的班级 MakesANetworkCall 实施原始类型供应商而不是供应商<字符串> 。这将有效地禁用类型检查并隐藏您所做的所有错误,因此这不是您应该担心的单一警告,因为这不是代码中唯一的错误:

First of all, your class MakesANetworkCall implements the raw type Supplier instead of Supplier<String>. This will effectively disable the type checking and hide all errors you made, so it’s not the single warning you should worry about, as that’s not the only thing wrong in your code:


  • BiConsumer 传递给 whenComplete 应该能够消耗 Throwable 作为第二个参数。

  • The BiConsumer passed to whenComplete should be able to consume a Throwable as its second argument.

函数传递给格外应使用 Throwable 并返回替代结果。

The Function passed to exceptionally should consume a Throwable and return an alternative result.

此外,您使用表达式 new CompletableFuture< String>ctor调用 static 方法;()作为其目标,你有一个过时的字符串创建表达式为 new String(主要汤姆报告!)其中简单常量主要汤姆报道!会做。通常,您似乎总是尝试使用不恰当的方法,即设计用于消耗您不使用的东西的方法,或者用于提供您没有的方法的方法。考虑一下:

Further, you are invoking a static method using the expression new CompletableFuture<String>() as its target and you have an obsolete string creation expression as new String("Major Tom reporting!") where the simple constant "Major Tom reporting!" will do. Generally, you seem to try to always use an inappropriate method, i.e. one designed to consume things you don’t use or one for supplying a value where you don’t have one. Consider this:

CompletableFuture.supplyAsync(new MakesANetworkCall())
    .thenAccept(result -> System.out.println(result))
    .exceptionally(e -> { e.printStackTrace(); return null;})
    .thenRun(()->System.out.println("Last action of all!"));

这似乎是你的意图。如果您确保 MakesANetworkCall 正确实现供应商< String> ,则应该在没有任何警告的情况下进行编译。

This does what seems to be your intention. If you ensure that your MakesANetworkCall correctly implements Supplier<String>, this should compile without any warnings.

这篇关于使用CompletableFuture进行回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆