基于资源稀缺性的背压可观察

时间:2016-11-09 15:07:03

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

在RxJava 1 / RxScala中,如何在以下情况下对源可观察量进行节流/反压?

def fast: Observable[Foo] // Supports backpressure

def afterExpensiveOp: Observable[Bar] = 
    fast.flatMap(foo => Observable.from(expensiveOp(foo))

// Signature and behavior is out of my control
def expensiveOp(foo: Foo)(implicit ec: ExecutionContext): Future[Bar] = {
   if(noResources()) Future.failed(new OutOfResourcesException())
   else Future { Bar() }
}

可能的解决方案就是阻止直到。哪个有效,但这非常不优雅,可以防止同时发出多个请求:

def afterExpensiveOp: Observable[Bar] = fast.flatMap(foo => 
   Observable.just(Observable.from(expensiveOp(foo)).toBlocking.head)
)

1 个答案:

答案 0 :(得分:0)

flatMap有一个参数来限制并发订阅者的数量。如果您使用此flatMap为您处理背压。

def afterExpensiveOp = fast.flatMap(safeNumberOfConccurrentExpensiveOps, x => Observable.from(expensiveOp(x)))