简体   繁体   English

如何使用Square的Retrofit网络库实现异步回调

[英]How to implement an async Callback using Square's Retrofit networking library

As an iOS developer beginning to work with Android I came across Retrofit. 作为一名开始使用Android的iOS开发人员,我遇到了Retrofit。 I understand how to implement synchronous requests but am having trouble implementing asynchronous requests with success/failure callbacks. 我理解如何实现同步请求,但是在使用成功/失败回调实现异步请求时遇到了问题。 Specifically, the Callback syntax is unclear to me and there are no concrete examples of how to do this on the Retrofit website , the Square blogpost introducing Retrofit, or elsewhere that I've seen. 具体来说,回调语法对我来说并不清楚,并且没有具体的例子说明如何在Retrofit 网站 ,Square 博客引入Retrofit或我见过的其他地方做到这一点。 Can someone please post some example code on this? 有人可以发一些示例代码吗? I filed an issue in the Retrofit repo asking that they update the README with this info. 我在Retrofit repo中提出了一个问题,要求他们用这个信息更新README。

After some more research and just plain spending more time in the Android/Java world I figured this out, using the example from their docs. 经过一些更多的研究,只是花了更多时间在Android / Java世界中,我想出了这一点,使用他们的文档中的示例。

Interface: 接口:

@GET("/user/{id}/photo")  
void listUsers(@Path("id") int id, Callback<Photo> cb);

Implementation: 执行:

RestAdapter restAdapter = new RestAdapter.Builder()
            .setServer("baseURL")     
            .build();
ClientInterface service = restAdapter.create(ClientInterface.class);

Callback callback = new Callback() {
    @Override
    public void success(Object o, Response response) {

    }

    @Override
    public void failure(RetrofitError retrofitError) {

    }
};
service.listUsers(666, callback);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM