How to handle circular dependent observables in RxJS?

Say, for example, somewhere on the server there is a mapping between integers and names, and the web page provides simple input when the user can enter a number and is given the corresponding name.

In its basic form, this task 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 the query is only executed 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 it request$depends on cache$, which depends on a serverResponse$ which, in turn, depends on request$.

How to solve this problem?

+2
source share
1 answer

Subject - - , Observable (cache$) - (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$);
+3

Source: https://habr.com/ru/post/1658585/


All Articles