如何从Retrofit onResponse返回方法中的数据?

时间:2017-03-06 21:49:32

标签: java android retrofit2

我是改装的新手,我想让我的getData方法返回一个功能对象。最简单的方法是什么?

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 个答案:

答案 0 :(得分:4)

你不能return,你必须“回电”。

将内部Callback类提取为参数。

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

在您的其他代码中

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

您也可以service.getData(new Callback<DataResponse>() { ... });