我有简单的 Observable。
public interface CitiesApi {
@GET("location/cities")
Observable<List<City>> getCities(@Query("country") String countryId);
}
我还有两个类(class):
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?
最佳答案
你应该使用 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
}
});
}
}
关于android - Rxjava2、Retrofit2 - 在两个类之间传输数据。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47772726/