改造2 onResponse将对象填充到另一个类中

时间:2018-12-19 12:55:57

标签: java android retrofit2

我正在尝试使用从请求中获得的值,但是由于onReponse方法无效,所以无法使用它们。我得到的值仅停留在onResponse方法中。我知道是因为它是空的,我什么也不能返回,但是有没有办法用我得到的值来填充对象?

这是我的ApiClient类:

public class ApiClient implements Callback<Map<String, Channel>> {

static final String BASE_URL = "some url";

public void start() {
    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

    RestInterface restInterface = retrofit.create(RestInterface.class);

    Call<Map<String, Channel>> call = restInterface.getChannels();
    call.enqueue(this);

}

@Override
public void onResponse(retrofit2.Call<Map<String, Channel>> call, Response<Map<String, Channel>> response) {
    System.out.println(response.code());
    if(response.isSuccessful()) {
        Map<String, Channel> body = response.body();
        List<Channel> channels = new ArrayList<>(body.values());
        for (Channel channel : body.values()) {
            System.out.println(channel.getSong());
        }
...

我要做的是使用从onResponse获得的值创建Channel对象。我试图在另一个这样的类中使用它:

    ApiClient apiClient = new ApiClient();

    apiClient.start();

,但它仍然仅在onResponse中有效。我需要创建Channel对象,例如:

Channel channel = new Channel(channels(1));

这,但在ApiClient中没有的另一个类中。

1 个答案:

答案 0 :(得分:0)

使用回调接口将数据传递给另一个类:

public interface ChannelCallback {

    void setChannels(Map<String, Channel> body);
}

在您的ApiClient中分配监听器:

private ChannelCallback listener;

public void start(ChannelCallback listener) {

    this.listener = listener;

    Gson gson = new GsonBuilder()
        .setLenient()
        .create();

    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

    RestInterface restInterface = retrofit.create(RestInterface.class);

    Call<Map<String, Channel>> call = restInterface.getChannels();
    call.enqueue(this);

}

在OnResponse中,通过此侦听器传递数据:

@Override
public void onResponse(retrofit2.Call<Map<String, Channel>> call, 
Response<Map<String, Channel>> response) {
    System.out.println(response.code());
    if(response.isSuccessful()) {
        Map<String, Channel> body = response.body();
        listener.setChannels(body);
}

不要忘记在调用ApiClient.start(this)的类中实现ChannelCallback侦听器

public SomeClass implements ChannelCallback{

    ...

    apiClient.start(this);

    ...

    @Override
    setChannels(Map<String, Channel> body){
    // logic here with data from body
    }

   ...

}