我收到一个对象(城市),想要在不同的线程中发送这些数据(在手机屏幕上反映并保存到这个城市的数据库)。这是我的代码:
private CompositeSubscription subscriptions;
...
@Override
public void onAddButtonClick(String cityName) {
Observable<City> obs = repository.getCity(cityName);
if (obs != null){
Subscription subscription = obs
.subscribeOn(backgroundThread)
.observeOn(mainThread)
.subscribe(
city -> {
view.cityExists();
repository.saveCityToDb(city);
}
);
subscriptions.add(subscription);
} else {
view.showCouldNotFindCity();
}
}
@Override
public void subscribe() {
subscriptions = new CompositeSubscription();
}
@Override
public void unsubscribe() {
subscriptions.clear();
}
所以这个方法view.cityExists();
我想在后台线程的UI线程和repository.saveCityToDb(city);
上运行。我该怎么办?
方法getCity(...);
返回Observable<City>
:
public Observable<City> getCity(String name){
return fileRepository.getCityFromFile(name);
}
答案 0 :(得分:2)
这应该可以解决问题:
Subscription subscription = obs
.subscribeOn(backgroundThread)
.doOnNext(city -> view.cityExists())
.observeOn(mainThread)
.subscribe(repository::saveCityToDb);
答案 1 :(得分:0)
您可能会寻找flatMap
运营商。它允许在与Observable
相同的线程中进行操作(它转换Observable
)。
Subscription subscription = obs
.subscribeOn(backgroundThread)
.flatMap(repository::saveCityToDb)
.observeOn(mainThread)
.subscribe(city -> view.cityExists());
记住,那个功能
repository::saveCityToDb
必须返回Observable
的内容才能继续。我建议它返回对象Observable.just(city)
。