Can RxJS be used differently?

The examples in RxJS README seem to suggest that we should subscribe to the source. In other words: we are waiting for the source to send events. In this sense, the sources seem push-based : the source decides when it creates new elements.

This contrasts, however, with iterators, where strictly speaking, new elements need to be created only when requested , that is, when called next(). This behavior pull-based, also known as the lazy generation.

For example, a stream may return all Wikipedia pages for primes. Elements are created only if you request them, because the generation of all of them is quite investment, and perhaps only 2 or 3 of them can be read in any case.

Can RxJS also have this pull-based behavior, so that new elements are only generated when they are requested?

The backpressure page seems to indicate that this is not yet possible.

+4
source share
2 answers

The short answer is no.

RxJS , , , , Iterator Observable. Observables , , .

, , , , . 1) 2) .

, Rx.Net, RxJS.

+2

, , , , .

var controlled = source.controlled();

// this callback will only be invoked after controlled.request()
controlled.subscribe(n => {
  log("controlled: " + n);
  // do some work, then signal for next value
  setTimeout(() => controlled.request(1), 2500);
});

controlled.request(1);

, , .

, , .

var output = document.getElementById("output");
var log = function(str) {
  output.value += "\n" + str;
  output.scrollTop = output.scrollHeight;
};

var source = Rx.Observable.timer(0, 1000);
source.subscribe(n => log("source: " + n));

var controlled = source.controlled();
// this callback will only be invoked after controlled.request()
controlled.subscribe(n => {
  log("controlled: " + n);
  // do some work, then signal for next value
  setTimeout(() => controlled.request(1), 2500);
});
controlled.request(1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/2.5.2/rx.all.js"></script>

<body>
  <textarea id="output" style="width:150px; height: 150px"></textarea>
</body>
Hide result
+1

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


All Articles