【问题标题】:switchIfEmpty is always calledswitchIfEmpty 总是被调用
【发布时间】:2020-08-07 23:51:25
【问题描述】:

我有这样的方法:

fun getActiveVersionWithCacheMiss(type: String): Mono<ActiveVersion> {
        return activeVersionRepository.findByType(type)
                .switchIfEmpty(
                        Mono.defer(return persist(ActiveVersion(type,1)))
                )
    }

persist 方法是一种保存活动版本的简单方法:

fun persist(activeVersion: ActiveVersion): Mono<ActiveVersion>{...}

在我的测试中,我模拟了 activeVersionRepository 以返回 findByType 的简单值。在调试期间activeVersionRepository.findByType(type).block() 评估为一个值并且绝对不为空。 我想知道为什么尽管使用了 defer switchIfEmpty 仍然被调用?

【问题讨论】:

    标签: kotlin reactive-programming reactor


    【解决方案1】:

    问题是return。无论findByType 是否发出值,都需要评估switchIfEmpty 的参数,这意味着需要评估defer 的参数,并且return 将在整个函数getActiveVersionWithCacheMiss 之外返回。

    虽然我看不出这段代码是如何编译的; return persist(...) 没有 Mono.defer 可以使用的值。你真的有大括号{},而不是括号()吗?

    【讨论】:

    • 当我在 persist() 之前删除返回时,它给了我以下错误:Error:(30, 30) Kotlin: Type inference failed: fun &lt;T : Any!&gt; defer(p0: Supplier&lt;out Mono&lt;out T!&gt;!&gt;): Mono&lt;T!&gt; cannot be applied to (Mono&lt;ActiveVersion&gt;) 关于第二部分,我没有明白你所说的 {} 或 () 的意思
    • 类似Mono.defer { return persist(ActiveVersion(type,1)) }。我猜你实际上需要Mono.defer { persist(ActiveVersion(type,1)) }Mono.defer(Supplier&lt;Mono&lt;ActiveVersion&gt;&gt; { persist(ActiveVersion(type,1)) })
    • 正如你所说,用大括号替换括号解决了这个问题,谢谢。
    猜你喜欢
    • 2019-06-19
    • 2021-05-02
    • 2017-09-14
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多