Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

java - 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. 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. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...