gpt4 book ai didi

java - Rxjava with retrofit - zip() - 如何绕过错误响应

转载 作者:搜寻专家 更新时间:2023-11-01 08:30:48 25 4
gpt4 key购买 nike

我正在尝试同时请求 3 项服务,并在所有服务都完成后显示结果。一切正常,直到其中一个请求失败。

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

testZip();
}

private void testZip() {
Retrofit repo = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();

Observable<JsonObject> userObservable = repo
.create(GitHubUser.class)
// .getUser("username")
.getUser("fakeUser_fakeUser")
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());

Observable<JsonArray> eventsObservable = repo
.create(GitHubEvents.class)
.listEvents("username")
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());

Observable<UserAndEvents> combined = Observable.zip(userObservable, eventsObservable, new Func2<JsonObject, JsonArray, UserAndEvents>() {
@Override
public UserAndEvents call(JsonObject jsonObject, JsonArray jsonElements) {
return new UserAndEvents(jsonObject, jsonElements);
}
}).onErrorResumeNext(Observable.<UserAndEvents>empty());

combined.subscribe(new Subscriber<UserAndEvents>() {
@Override
public void onCompleted() {
Log.wtf("TAG", "onCompleted");
}

@Override
public void onError(Throwable e) {
Log.wtf("TAG", "onError");
Log.wtf("TAG", e.toString());
}

@Override
public void onNext(UserAndEvents o) {
Log.wtf("TAG", "onNext");
Log.wtf("Username", o.user.get("name").toString());
Log.wtf("First event", o.events.get(0).getAsJsonObject().get("type").toString());
}
});
}



public interface GitHubUser {
@GET("users/{user}")
Observable<JsonObject> getUser(@Path("user") String user);
}

public interface GitHubEvents {
@GET("users/{user}/events")
Observable<JsonArray> listEvents(@Path("user") String user);
}

public class UserAndEvents {
public UserAndEvents(JsonObject user, JsonArray events) {
this.events = events;
this.user = user;
}

public JsonArray events;
public JsonObject user;
}

我在这里想要的是即使用户请求失败也能得到“事件”数据。我确实尝试过 onErrorReturn()、onErrorResumeNext()、onExceptionResumeNext(),但它们都在没有数据的情况下转到 onCompleted()。我打算使用 mergeDelayError() 但它要求响应数据相同,这不适合我的应用程序。

最佳答案

移动onErrorResumeNextuserObservable , 所以 zip看起来像 Observable<UserAndEvents> combined = Observable.zip(userObservable.onErrorResumeNext(Observable.just(new JsonObject()), eventsObservable,... .如果出现错误,压缩结果将包含用户的空 JsonObject。

关于java - Rxjava with retrofit - zip() - 如何绕过错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41073313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com