RxJS - Fire Signs OK

I am trying to figure out an RxJS template for declaring my “subscribers” which they execute in order.

Here's the situation I'm in:

var flag = false;

// Stream that non-deterministically emits `true` when flag is true
var random$ = Rx.Observable.interval(1000)
  .map(() => setFlagToRandomTrueOrFalse())
  .filter(x => x)
  .first();

// How can I declare my "subscribes" so that the console.logs happen in order?
var sub1 = random$.subscribe(() => console.log(1), console.log, resetFlagToFalse);
var sub2 = random$.subscribe(() => console.log(2), console.log, resetFlagToFalse);

function setFlagToRandomTrueOrFalse() {
  flag = flag || !!Math.floor(Math.random() * 2);
  return flag;
}

function resetFlagToFalse() { flag = false; }

Currently, it prints 1and 2randomly due to the asynchronous nature .subscribe.

Also, what is the name for these “subscribers”? All in all here is RxJS noob.

+4
source share
2 answers

I'm not sure that you are keeping order due to the asynchronous nature subscribe.

, , random$ , , . , . , , , , , , .

- : "" "" ? , , , , , - Rxjs.

, .. , ( ), ( ), multicast , . ,

var random$ = Rx.Observable.interval(1000)
    .map(() => setFlagToRandomTrueOrFalse())
    .filter(x => x)
    .share();

, , . , , . , multicast -like , ( ) , , . , RxJS? ,

, , . , flag, .

, Rxjs: ,

+3

publish() and connect() ,

var flag = false;

// Stream that non-deterministically emits `true` when flag is true
var random$ = Rx.Observable.interval(1000)
    .map(() => setFlagToRandomTrueOrFalse())
    .filter(x => x)
    .first().publish();

// How can I declare my "subscribes" so that the console.logs happen in order?
var sub1 = random$.subscribe(() => console.log(1), console.log, resetFlagToFalse);
var sub2 = random$.subscribe(() => console.log(2), console.log, resetFlagToFalse);

random$.connect();

function setFlagToRandomTrueOrFalse() {
    flag = flag || !!Math.floor(Math.random() * 2);
    return flag;
}

function resetFlagToFalse() { flag = false; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.all.js"></script>
Hide result
+1

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


All Articles