问题
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( ... );
But now request$
depends on cache$
which depends on a serverResponse$
which in turn depends on request$
.
How do I solve this problem?
回答1:
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$);
来源:https://stackoverflow.com/questions/34343869/how-to-handle-circularly-dependent-observables-in-rxjs