使用RxJava(ReactiveX)运行Observable需要多长时间?

时间:2016-04-27 20:33:09

标签: java scala rx-java reactive-programming reactivex

我在scala Play Framework 2.5中使用Java ReactiveX(RxJava)与couchbase异步通信我想知道我的observable运行需要多长时间?我使用下面的代码定义了我的observable。

def get(id: String) : Observable[Profile] = {
  this.bucket
    .async()
    // can I have a start time here possibly using map?
    .get(id)
    .map[Profile](toProfile)
    // can I have an end time here possibly using map?
}

我使用以下

来调用它
Thread.sleep(1000)

val observable = get("myID")

Thread.sleep(1000)

// measure start time here
println("observable: " + observable.toBlocking.first())
// measure end time here

Thread.sleep(1000)

如何衡量observable运行所需的时间?

提前感谢你

弗朗西斯

1 个答案:

答案 0 :(得分:9)

您需要在doOnSubscribe()块中启动计时器,然后在onTerminated()中完成。

一个例子可能是:

long start;
observable()
    .doOnSubscribe(() -> start = System.nanoTime())
    .doOnTerminate(() -> System.out.println(System.nanoTime() - start));

或者你可以按照Netflix对RxNetty的处理方式,将开始时间作为流经链的对象的一部分返回,并在最后使用它。