简体   繁体   English

RxJava:如何包装多步操作,将完成的步骤返回给观察者?

[英]RxJava: How can I wrap a multi-step operation, returning the step complete to observers?

Lets say I have a login and user data method, representing HTTP calls: 可以说我有一个登录和用户数据方法,代表HTTP调用:

Single<LoginResponse> login();
Single<UserData> userData();

I need to call login() then userData() . 我需要先调用login()然后再调用userData() If both succeed, the user is logged in. 如果两个都成功,则用户已登录。

I know how to wrap them up in a eg Completable : 我知道如何将它们包装在例如Completable

Completable performLogin() {
    login().doOnSuccess(this::storeLoginResponse)
        .flatMap(userData())
        .doOnSuccess(this::storeUserData)
        .doOnError(this::wipeLoginData)
        .toCompletable();
}

So the UI then says 所以用户界面然后说

showLoading();
performLogin().subscribe(() -> {
    stopLoading();
    onLoginSuccess();
}, error -> {
    stopLoading();
    onLoginFailure();
});

What if the UI needs to show which stage of the loading is happening? 如果UI需要显示正在加载的哪个阶段怎么办? As in, when the login() call completes and the userData() call starts it will change the UI? 如上,当login()调用完成并且userData()调用开始时,它将更改UI?

What I thought of is something like 我想到的是这样的

Observable<LoginStage> performLogin() {
    return Observable.create(emitter -> {
        login.doOnSuccess(response -> {
            storeLoginResponse(response)
            emitter.onNext(LOGIN_COMPLETE)
        }).flatMap(userData())
        .subscribe(userData -> {
            storeUserData(userData);
            emitter.onNext(USER_DATA_COMPLETE)
            emitter.onComplete();
        }, error -> {
            wipeLoginData();
            emitter.onError(error);
        });
    });
}

But it feels like there's a nicer or more Rx-y way to do it. 但是感觉上有更好的或更多的接收方法。

You can use hot observables and chain one observable to another Subject and pass all items form one emission to another if you need it. 您可以使用热的可观测值,并将一个可观测值链接到另一个主题,并在需要时将所有项从一个发射传递给另一个。

@Test
public void chainObservablesWithSubject() throws InterruptedException {
    Observable<Long> observable = Observable.from(Arrays.asList(1l, 2l, 3l, 4l));
    Subject<Long, Long> chainObservable = ReplaySubject.create(1);
    observable.subscribe(chainObservable);
    chainObservable.subscribe(System.out::println, (e) -> System.err.println(e.getMessage()), System.out::println);
}

You can check more examples here https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/connectable/HotObservable.java 您可以在这里查看更多示例https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/connectable/HotObservable.java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM