How can I return data in method from Retrofit onResponse?

青春壹個敷衍的年華 提交于 2019-12-01 17:38:51

问题


I'm new with retrofit and I want to make my getData method to return a feature object. What is the easiest way to do that?

DataService.java

public class DataService {

    private static final String TAG = MainActivity.class.getSimpleName();
    private final ApiClient apiClient;

    public DataService() {
        apiClient = new ApiClientFactory().createApiClient();
    }

    public List<Feature> getData(){

        apiClient.getData().enqueue(new Callback<DataResponse>() {

            @Override
            public void onResponse(Call<DataResponse> call, Response<DataResponse> response) {
                List<Feature> features = response.body().getFeatures();
                Log.d(TAG, "Data successfully downloaded");
            }

            @Override
            public void onFailure(Call<DataResponse> call, Throwable t) {
                Log.e(TAG, t.toString());
            }
        });
        //I need to return features in getData method
    }
}

回答1:


You can't return, you must "call back".

Extract that inner Callback class to a parameter.

public void getData(Callback<DataResponse> callback){
    apiClient.getData().enqueue(callback);
}

In your other code

// DataService service = ...;

// Define Callback
Callback<DataResponse> responseCallback = new Callback<DataResponse>() {

    @Override
    public void onResponse(Call<DataResponse> call, Response<DataResponse> response) {
        List<Feature> features = response.body().getFeatures();
        Log.d(TAG, "Data successfully downloaded");

        // Data is returned here
        for (Feature f: features) {
            Log.d("feature", String.valueOf(f)); // for example
        }
    }

    @Override
    public void onFailure(Call<DataResponse> call, Throwable t) {
        Log.e(TAG, t.toString());
    }
};

// Call it
service.getData(responseCallback);

You can also do service.getData(new Callback<DataResponse>() { ... });



来源:https://stackoverflow.com/questions/42636247/how-can-i-return-data-in-method-from-retrofit-onresponse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!