如何在RxJS中处理循环依赖的可观察变量? [英] How to handle circularly dependent observables in RxJS?
问题描述
比如说在服务器上的某个位置之间存在一个映射 整数和名称,网页在用户提供简单输入的地方 可以输入一个数字并为其指定相应的名称.
Let's say e.g. that somewhere on a server there is a mapping between integers and names and a web page provides a simple input where a user can enter a number and is given the corresponding name.
从根本上讲,这个问题很简单:
In its basic form, this problem is simple:
const input$ = Rx.Observable.fromEvent(..., "input");
const request$ = input$.map( ... );
const serverResponse$ = request$.flatMap( askServer );
现在,我想缓存结果,以便仅请求 当号码不在缓存中时完成.
Now I would like to cache the results so that a request is only done when the number is not in the cache.
const input$ = Rx.Observable.fromEvent(..., "input");
// request$ should now also depend on cache$
const request$ = ???;
const serverResponse$ = request$.flatMap( askServer );
const cache$ = serverResponse$.scan( ... );
但是现在request$
取决于cache$
,而cache$
取决于serverResponse$
反过来取决于request$
.
But now request$
depends on cache$
which depends on a serverResponse$
which in turn depends on request$
.
我该如何解决这个问题?
How do I solve this problem?
推荐答案
在依赖图中的循环中的某个时刻引入Subject
作为代理,然后将实际的Observable(cache$
)的行为镜像到代理主题(proxyCache$
).
Introduce a Subject
as a proxy at some point in the cycle in the dependency graph, then mirror the behavior of the real Observable (cache$
) onto the proxy Subject (proxyCache$
).
const input$ = Rx.Observable.fromEvent(..., "input");
const proxyCache$ = new Rx.Subject();
const request$ = input$.merge(proxyCache$).map( ... );
const serverResponse$ = request$.flatMap( askServer );
const cache$ = serverResponse$.scan( ... );
cache$.subscribe(proxyCache$);
这篇关于如何在RxJS中处理循环依赖的可观察变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!