如果我们有可观察的:
1 -> 2 -> 3 -> 4 -> 5 -> ...
如何构造新的 observable:
(1, 2) -> (3, 4) -> ...
也许问题很短,但我真的找不到如何实现。谢谢
谢谢大家,我找到了一种方法并考虑删除var
import java.util.concurrent.TimeUnit
import rx.lang.scala.{Subject, Observable}
import scala.concurrent.duration.Duration
object ObservableEx {
implicit class ObservableImpl[T](src: Observable[T]) {
/**
* 1 -> 2 -> 3 -> 4 ->...
* (1,2) -> (3,4) -> ...
*/
def pair: Observable[(T, T)] = {
val sub = Subject[(T, T)]()
var former: Option[T] = None //help me to kill it
src.subscribe(
x => {
if (former.isEmpty) {
former = Some(x)
}
else {
sub.onNext(former.get, x)
former = None
}
},
e => sub.onError(e),
() => sub.onCompleted()
)
sub
}
}
}
object Test extends App {
import ObservableEx._
val pair = Observable.interval(Duration(1L, TimeUnit.SECONDS)).pair
pair.subscribe(x => println("1 - " + x))
pair.subscribe(x => println("2 - " + x))
Thread.currentThread().join()
}
我根本不喜欢 var,再次感谢!
最后 我得到了一个轻松的方式,希望可以帮助别人。
def pairPure[T](src: Observable[T]): Observable[(T, T)] = {
def pendingPair(former: Option[T], sub: Subject[(T, T)]): Unit = {
val p = Promise[Unit]
val subscription = src.subscribe(
x => {
if (former.isEmpty) {
p.trySuccess(Unit)
pendingPair(Some(x), sub)
}
else {
sub.onNext(former.get, x)
p.trySuccess(Unit)
pendingPair(None, sub)
}
},
e => sub.onError(e),
() => sub.onCompleted()
)
p.future.map{x => subscription.unsubscribe()}
}
val sub = Subject[(T,T)]()
pendingPair(None, sub)
sub
}
其他答案也很有帮助~