在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)
)
答案 0 :(得分:0)
flatMap有一个参数来限制并发订阅者的数量。如果您使用此flatMap为您处理背压。
def afterExpensiveOp = fast.flatMap(safeNumberOfConccurrentExpensiveOps, x => Observable.from(expensiveOp(x)))