How to handle circularly dependent observables in RxJS?

≯℡__Kan透↙ 提交于 2019-12-06 11:30:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!