【问题标题】:Handling multiple requests returning the same type in Retrofit在 Retrofit 中处理返回相同类型的多个请求
【发布时间】:2016-02-24 20:15:58
【问题描述】:

我有一个这样设置的片段:

public mFragment extends Fragment implements Callback<mType> {

    ...

@Override
public void onViewCreated(View v, Bundle sis) {
    Retrofit retrofit = new Retrofit.Builder().baseUrl("MYURL").addConverterFactory(GsonConverterFactory.create()).build();
    api mAPI = retrofit.create(api.class);
    Call<mType> call1 = mAPI.query1("query1"));
    Call<mType> call2 = mAPI.query2("query2"));
    call1.enqueue(this);
    call2.enqueue(this);
}

@Override
public void onFailure(Throwable t) {
    ...
}

@Override
public void onResponse(final Response<mType> response, Retrofit retrofit) {
    ...
}
}

我需要进行 2 个 api 调用,它们都返回相同的类型。但是,我想用不同的 onResponse 方法处理它们,因为我需要对它们做不同的事情。这是在改造 2.0 下。 这是不同服务的 API,因此我无权更改任何响应。

有没有办法指定 Retrofit Call 回调到哪个方法?我真的希望这有一个干净的解决方案,就好像我使用两种不同的返回类型一样。如果最坏的情况发生,我可以复制对象并重命名它,但我认为有一个“正确”的方法来做到这一点。

【问题讨论】:

    标签: android retrofit


    【解决方案1】:

    单独排列您的请求。所以你的响应监听器对于两个请求都是分开的

    call1.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Response<String> response) {
        }
    
        @Override
        public void onFailure(Throwable t) {
        }
    });
    

    call2.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Response<String> response) {
        }
    
        @Override
        public void onFailure(Throwable t) {
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-11-25
      • 1970-01-01
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      相关资源
      最近更新 更多