【问题标题】:Returning value from callback to its parent从回调返回值到其父级
【发布时间】:2020-07-14 04:29:09
【问题描述】:

我需要将休息服务调用所获得的值返回给它的父级。问题是我正在调用休息服务(使用异步回调类),所以我需要“等待”结果,然后将其传递给其他地方。请查看以下sn-p。

config.addC(AppController.LOCALE.getMod(),new StringC<SomeEntry>() {
public String getValue(SomeEntry object) {
            Rest.getSomething(AppController.getRest(),  object.getId(), idAccess, null, null,  new AsyncCallback<SomeStructureList>() {

                @Override
                public void onSuccess(final SomeStructureList result) {
                    return result.getSometing().getSomethingElse(); // i need to have access to variable result in the parent function getValue()
                }

                @Override
                public void onFailure(Throwable caught) {
                    // fail...
                }
            });

            return getRes(); //TODO as well
        }
});

这样做的正确方法是什么?提前致谢。 编辑:我添加了更多代码以使其更清晰。

【问题讨论】:

    标签: java rest gwt asynccallback


    【解决方案1】:

    一种方法是定义一个接口:

    public interface GetValueCallback() {
        onSuccess(SomeStructureList result);
    }
    

    然后为实现该接口的 getValue 方法设置一个回调参数:

    public String getValue(SomeEntry object, GetValueCallback callback) {
        Rest.getSomething(AppController.getRest(),  object.getId(), idAccess, null, null,  new AsyncCallback<SomeStructureList>() {
    
            @Override
            public void onSuccess(final SomeStructureList result) {
                callback.onSuccess(result);
            }
    
            @Override
            public void onFailure(Throwable caught) {
                // fail...
            }
        });
    
        return getRes(); //TODO as well
    }
    

    最后,通过传递回调来执行调用,您将收到结果作为参数:

    getValue(object, new Callback() {
        @Override
        public void onSuccess(SomeStructureList result) {
            // You can do whatever you need with the result here
        }
    });
    

    如果你对其他方面感兴趣,你也可以看看 RxJava。

    【讨论】:

    • 您的代码对我不起作用,请您仔细检查一下是否有错别字/错误?谢谢。
    • 嗯,你更新了问题,这个StringC是在哪里定义的?
    【解决方案2】:

    嗯,它应该反过来。你习惯于调用像getValue 这样的方法,然后对结果做一些事情。现在你必须使用onSuccess 方法来做你想做的事。如果需要,您可以在 getValue 回调函数中作为参数传递,该回调函数可以在 onSuccess 方法中执行。

    【讨论】:

    • 我不这么认为。如您所见,我在休息调用中使用参数object
    • 我的想法和@jeprubio 写的完全一样。也许我没有正确解释。
    猜你喜欢
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    • 2013-08-13
    • 2010-10-01
    • 2012-03-27
    • 1970-01-01
    相关资源
    最近更新 更多