我有简单的Observable。
public interface CitiesApi {
@GET("location/cities")
Observable<List<City>> getCities(@Query("country") String countryId);
}
我也有两节课:
class Manager {
List<City> mList = new ArrayList();
public Observable<List<City>> getCitiesObservable(String countryId) {
// I want to update mList value in each new request;
return CitiesApi.getCities(countryId);
}
第二课:
class Presenter {
public void request() {
Manager.getCitiesObservable("us")
.subscribeOn(Schedulers.newThread)
.observeOn(AndroidSchedulers.mainThread)
.subscribe(new ......)
}
正如您所看到的,我写了一条评论“我想在每个新请求中更新mList值”。 每次Presenter发出请求时,如何更新Manager类中的mList?
答案 0 :(得分:2)
您应该使用RxJava的转换运算符(如map
)来实现您想要的功能。以下是所有运营商的列表 - ReactiveX - Operators
以下是你可以做到的:
class Manager {
List<City> mList = new ArrayList();
public Observable<List<City>> getCitiesObservable(String countryId) {
return CitiesApi.getCities(countryId)
.subscribeOn(Schedulers.io())
.map(new Function<List<City>, List<City>>() {
@Override
public List<City> apply(List<City> cities) throws Exception {
// Do your stuff and return a List<City> object
}
});
}
}
答案 1 :(得分:0)
好的,这是我承诺的:
考虑设置适配器并准备好mList
,我这样做。
调用请求并将响应主体置于变量
private void makeGetMyChatsRequest(String searchWord){
RestClient.getApi().getChats(searchWord).enqueue(new Callback<Chats>() {
@Override
public void onResponse(Call<Chats> call, Response<Chats> response) {
if (response.isSuccessful())
if (response.code() == 200){
chatsDatas = response.body().getChats();
chatAdapter.notifiDataSetChanged();
}
}
@Override
public void onFailure(Call<Chats> call, Throwable t) {
Log.d(TAG, "-=onFailure=-\n" + t.getMessage());
}
});
}
这是改装界面
@GET(RestClient.API_GET_CHATS)
Call<Chats> getChats(@Query("username") String username);
它响应的type
对象,在我的情况下<Chats>
public class Chats implements Serializable {
private ArrayList<ChatsData> chats;
public ArrayList<ChatsData> getChats() {
return chats;
}
public void setChats(ArrayList<ChatsData> chats) {
this.chats = chats;
}
}
因为我有一个数据数组,我还定义了这个数组中的数据类型(在请求调用函数中将传递给chatsDatas
变量的确切数据。
public class ChatsData implements Serializable {
private int chat_room_id;
private int read;
private int user_id;
private String name;
private String picture;
private int is_online;
private LastMessageData last_message;
//here will be getters & setters for each field
}