问题描述
val x: Observable[Int] = Observable.just(1).doOnSubscribe(() => println(s"subscribed"))
val y = x.subscribe(t => println(s"got item: $t"))
println("all done")
我以为这段代码会打印
subscribed
got item: 1
all done
但是它不会显示初始的"subscribed".
But it doesn't print the initial "subscribed".
推荐答案
doOnSubscribe
的签名是:
def doOnSubscribe(onSubscribe: => Unit): Observable[T]
也就是说,它需要一个 by-name 参数.因此,您必须按以下方式使用它:
That is, it takes a by-name argument. So you have to use it as follows:
Observable.just(1).doOnSubscribe(println(s"subscribed"))
按名称表示println
传递给doOnSubscribe
时将不执行,只有doOnSubscribe
使用它时才会执行.
by-name means that the println
will not be executed when passed to doOnSubscribe
, but only once doOnSubscribe
uses it.
您传递给doOnSubscribe
的是一个0 arity函数,即类型为() => Unit
的表达式,并且通过舍弃表达式的值,Scala可以将任何表达式转换为Unit,因此才进行编译.
What you were passing to doOnSubscribe
is a 0-arity function, i.e. an expression of type () => Unit
, and by discarding the value of an expression, Scala can turn any expression into Unit, so that's why it compiled.
恕我直言,这很令人困惑,我更喜欢使用() => Unit
而不是=> Unit
的参数,然后它将按您的预期工作.
This is IMHO confusing, and I'd prefer a () => Unit
argument instead of => Unit
, then it would work as you expected.
顺便说一句:您不是第一个为此而感到困惑的人;-)
这篇关于为什么这不执行为RxScala的doOnSubscribe函数提供的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!