然后在完成之前执行 [英] AndThen executes before completable finished

查看:96
本文介绍了然后在完成之前执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们采用两种用Rx编写的方法:

Let's take two methods written with Rx:

Maybe<Foo> getFooFromLocal
Single<Foo> getFooFromNetwork

当我们检查本地存储中的 Foo 时,我想写一个链.如果没有 Foo ,我们应该从网络上获取它,然后将其保存到本地存储中,然后再次从本地存储中获取它,并将其传递给我们的订户.

I want to write a chain when we check our local storage for Foo. If we don't have any Foo we should get it from the network then save it to the local storage and again get it from local storage and pass it to our subscriber.

storage
            .getFooFromLocal()
            .switchIfEmpty(network.getFooFromNetwork().map { it[0] }
                    .flatMapCompletable { storage.saveFoo(it) }
                    .andThen(storage.getFooFromLocal()))
                    .subscriber(/**/)

问题在于andThen部分在可完成传递到flatMapCompletable之前完成.我发现,如果包装到Maybe.defer{},则可以摆脱此问题.但是根据andThen的文档

The problem is that andThen part completes before completable passed into flatMapCompletable. I found out that I can get rid of this problem if I wrap into Maybe.defer{}. But according to the documentation of andThen it

返回一个Maybe,它将订阅此Completable.

Returns a Maybe which will subscribe to this Completable.

也许已经

表示递延的计算和可能的值或异常的发出

Represents a deferred computation and emission of a maybe value or exception

所以问题是为什么我的andThen部分在可完成完成之前运行.编写此类链的最佳和优雅方法是什么.

So the question is why my andThen part run before completable finished. And what is the best and elegant way to write such chains.

通话记录:

06:05:58.803 getFooFromLocal
06:05:58.804 getFooFromLocal
06:05:58.804 getFooFromNetwork
06:05:59.963 saveFoo

推荐答案

这对我有用:

public class AndThenTest {

    Integer value;

    @Test
    public void test() {
        getFromLocal()
        .switchIfEmpty(getFromNetwork()
                .flatMapCompletable(v -> saveFoo(v))
                .andThen(getFromLocal()))
        .doOnSuccess(e -> System.out.println("Success: " + e))
        .test()
        .awaitDone(5, TimeUnit.SECONDS)
        .assertResult(10);
    }

    Maybe<Integer> getFromLocal() {
        return Maybe.fromCallable(() -> {
            System.out.println("FromLocal called");
            return value;
        });
    }

    Single<Integer> getFromNetwork() {
        return Single.fromCallable(() -> {
            System.out.println("FromNetwork called");
            return 10;
        }).delay(100, TimeUnit.MILLISECONDS)
                ;
    }

    Completable saveFoo(Integer v) {
        return Completable.fromRunnable(() -> {
            System.out.println("SaveFoo called");
            value = v;
        });
    }
}

并打印:

FromLocal called
FromNetwork called
SaveFoo called
FromLocal called
Success: 10

所以我的猜测是,您未显示的方法之一存在错误.

So my guess is that there is a mistake in one of the methods you are not showing.

这篇关于然后在完成之前执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆