Why doesn't this execute the function given for RxScala's doOnSubscribe function?

℡╲_俬逩灬. 提交于 2020-01-06 14:41:11

问题


  val x: Observable[Int] = Observable.just(1).doOnSubscribe(() => println(s"subscribed"))
  val y = x.subscribe(t => println(s"got item: $t"))
  println("all done")

I would have thought this code would print

subscribed
got item: 1
all done

But it doesn't print the initial "subscribed".


回答1:


The signature of doOnSubscribe is:

def doOnSubscribe(onSubscribe: => Unit): Observable[T] 

That is, it takes a by-name argument. So you have to use it as follows:

Observable.just(1).doOnSubscribe(println(s"subscribed"))

by-name means that the println will not be executed when passed to doOnSubscribe, but only once doOnSubscribe uses it.

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.

This is IMHO confusing, and I'd prefer a () => Unit argument instead of => Unit, then it would work as you expected.

Btw: you are not the first to be puzzled by this ;-)



来源:https://stackoverflow.com/questions/36274683/why-doesnt-this-execute-the-function-given-for-rxscalas-doonsubscribe-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!