0

I want to get a stream which emits numbers and each number is distinct from the previous one or the all previous numbers.

The stream below outputs may be [0, 1, 1, 1, 2, 1, 0, ...], I expect some modifications to get [0, 2, 1, 2, 0, 1, ...], no two or more adjacent numbers are same in the sequence:

const number$ = Rx.Observable.interval(500)
  .map(() => Math.floor(Math.random() * 3))

number$.subscribe(console.log)

The stream below outputs may be [3, 3, 1, 4, 3], I expect some modifications to get [2, 0, 3, 1, 4], all numbers are distinct:

const number$ = Rx.Observable.interval(500)
  .map(() => Math.floor(Math.random() * 5))
  .take(5)

number$.subscribe(console.log)

Simply using distinct and distinctUntilChanged will make some 'holes', it isn't desired. Pre-generate the determinated sequence(ex: using lodash.shuffle) is also not the desired solution, the output number is may generated by a remote rand generator service, means that we cloud retry number fetching while get duplicated numbers.

I think if there are some ways to get the comparison result of distinct and distinctUntilChanged and using it to conditionally rollback/replay the last (one or some) operation(s) can solve my problem.

Zheeeng
  • 642
  • 10
  • 21
  • for just not the same number, you could have a look here: [Random number, which is not equal to the previous number](https://stackoverflow.com/q/40056297/1447675) – Nina Scholz Jul 20 '17 at 07:15
  • @NinaScholz I want to get some related knowledge points like condition control in rx and operation rollback. Store the last random value outside the streams seems like anti the reactive way. – Zheeeng Jul 20 '17 at 08:18
  • part 2: maybe you consider to use an array with the values and apply a shuffling method, like [fisher-yates](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm) – Nina Scholz Jul 20 '17 at 11:05
  • @NinaScholz the 2nd stream can use the shuffled numbers, which are determined, but in real situation, I want to fetch a recommend user from remote, if it's already recommended, fetch through api again. – Zheeeng Jul 20 '17 at 12:32

0 Answers0