阻塞方法执行,直到异步RxJava调用返回



我很确定肯定有人以前问过这个问题,但我找不到。即使对于像我这样的RxJava初学者,我也在尝试做一些非常简单的事情

public ILocation findLocationDetails() {
requestLocationDetails();
return buildLocationFromDetails();
}

方法requestLocationDetails包含一个REST调用,该调用在另一个线程中执行:

private void requestLocationDetails() {
compositeDisposable.add(
Observable
.fromCallable((() -> JsonRestCaller.readJsonFromUrl(buildUrl())))
.subscribeOn(Schedulers.io())
.subscribeWith(new DisposableObserver<JsonObject>() {
@Override
public void onNext(JsonObject jsonObject) {
try {
parseJson(jsonObject);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
}
@Override
public void onError(Throwable e) {
Log.e(TAG, e.getMessage());
}
@Override
public void onComplete() {
}
}));
}

现在,我只想等待parseJson((完成,这样方法buildLocationFromDetails就可以处理在parseJon中检索到的详细信息。

我读过一些关于阻塞运算符的文章,但我不确定如何使它们在我的情况下工作。我还发现了一些例子,有人只是等了一段时间来确保结果可用,但我不知道要等多久,我觉得这不是正确的方法。

您可以尝试下面的

//Create a method which will parse json and return the result in String 
//(I am assuming string as parse response for simplicity)
public Observable<String> parseJson(JsonObject jsonObject) {
return Observable
.create(
e -> {
//parse json code goes here.
// Once parsing done pass the details
e.onNext("Details from parsing json");
e.onComplete();
}
);
}

现在修改上面的代码,你已经写,

Observable
.fromCallable((() -> JsonRestCaller.readJsonFromUrl(buildUrl())))
//Pass the jsonObject from above to parseJson() method
.flatMap(jsonObject -> parseJson(jsonObject))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
//details is the string from parsing json
.subscribe(
details -> buildLocationFromDetails(details),
error -> new Throwable(error)
);

希望这能有所帮助。

最新更新