为什么这不执行为RxScala的doOnSubscribe函数提供的功能? [英] Why doesn't this execute the function given for RxScala's doOnSubscribe function?

查看:177
本文介绍了为什么这不执行为RxScala的doOnSubscribe函数提供的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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函数提供的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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