Kotlin和RxJava-为什么我的Single.zip()无法编译? [英] Kotlin and RxJava - Why is my Single.zip() not compiling?

查看:261
本文介绍了Kotlin和RxJava-为什么我的Single.zip()无法编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要疯了.我正在尝试创建一个Observable<BigDecimal>扩展函数(针对RxJava 2.x)以发出发射的平均值,但是我遇到了Single.zip()函数的编译错误.有人知道我在做什么错吗?我也尝试对所有类型都明确,但这没用...

I'm going a little crazy here. I'm trying to create an Observable<BigDecimal> extension function (against RxJava 2.x) to emit the average of the emissions, but I'm getting a compile error with the Single.zip() function. Does anybody have any ideas what I'm doing wrong? I tried to be explicit with all my types too and that didn't work...

import io.reactivex.Observable
import io.reactivex.Single
import java.math.BigDecimal


fun Observable<BigDecimal>.sum() = reduce { total, next -> total + next }

//compile error
fun Observable<BigDecimal>.average() = publish().autoConnect(2).let {
    Single.zip(it.sum().toSingle(), it.count()) {
        sum, count -> sum / BigDecimal.valueOf(count)
    }
}

推荐答案

类型推断在rxJava2中通常不起作用.实际上,这不是类型推断问题. Kotlin通常会生成扩展方法,以用Kotlin功能类型替换SAM,但是由于某种原因,该技术无法用于替代方法.

Type inference mostly does not work for rxJava2. It's not a type inference problem actually. Kotlin usually generates extension methods to that replaces SAM with kotlin functional types, but this technic does not work for overridden methods for some reason.

此处有更多详细信息 https://youtrack.jetbrains.com/issue/KT-13609

作为一种选择,您可以尝试为lambda参数指定类型

As an option, you could try to specify types for lambda arguments

fun Observable<BigDecimal>.average() = publish().autoConnect(2).let {
    Single.zip(it.sum().toSingle(), it.count(), BiFunction {
        sum: BigDecimal, count: Long ->
        sum / BigDecimal.valueOf(count)
    })
}

这篇关于Kotlin和RxJava-为什么我的Single.zip()无法编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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