简体   繁体   English

在Scala中通过Observable实现和折叠

[英]materialize and foldLeft with Observable in Scala

Why this code never fires the subscription block? 为什么此代码从不触发订阅块?

Observable(1, 2, 3).materialize.foldLeft(0) { (acc, tn) =>
  tn match {
    case OnNext(n) => { println(acc, n); acc + n }
  }
}.subscribe({s => println("THIS IS NOT FIRED", s) })

This is the output: (0,1) (1,2) (3,3) 这是输出: (0,1) (1,2) (3,3)

I am a Scala beginner as well, so bear with me if anything is not explained properly. 我也是Scala初学者,所以如果没有正确解释,请多多包涵。
It seems that you are missing the onCompleted case: 似乎您缺少onCompleted案例:

Try it with: 尝试使用:

 Observable(1, 2, 3).materialize.foldLeft(0) { (acc, tn) =>
   tn match {
   case Notification.OnNext(n)  => { println(acc, n); acc + n }
   case Notification.OnCompleted() => acc
  }
}.subscribe({s => println("THIS IS NOW FIRED", s) })

But since the value returned from foldLeft is essentially one (the sum), it'd become more readable if we rewrite it as follows: 但是由于foldLeft返回的值本质上是一个(总和),因此,如果我们按以下方式重写它,它将变得更具可读性:

   val sum = Observable(1, 2, 3).materialize.foldLeft(0) { (acc, tn) =>
       tn match {
       case Notification.OnNext(n)  => { println(acc, n); acc + n }
       case Notification.OnCompleted() => acc
      }
    }.toBlockingObservable.single

   println(sum) // prints 6

Needless to say that the previous solutions hold True only for cases where there is no element in the stream that raises an Error. 不用说,先前的解决方案仅在流中没有引发错误的元素的情况下成立。

I found this link very helpful to understand Observables. 我发现此链接对于了解Observables非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM