How can I rewrite this countdown timer using RxPY?

105 views Asked by At

Here's RxJS code I'm trying to reproduce with RxPY.

const counter$ = interval(1000);
counter$
  .pipe(
    mapTo(-1),
    scan((accumulator, current) => {
      return accumulator + current;
    }, 10),
    takeWhile(value => value >= 0)
  )
  .subscribe(console.log);
9
8
7
6
5
4
3
2
1
0
-1

And here's what I through was equivalent but is not

counter = rx.interval(1)
composed = counter.pipe(
    ops.map(lambda value: value - 1),
    ops.scan(lambda acc, curr: acc + curr, 10),
    ops.take_while(lambda value: value >= 0),
)
composed.subscribe(lambda value: print(value))
9
9
10
12
15
19

Could someone help me to understand what I'm missing here?

1

There are 1 answers

1
BizzyBob On BEST ANSWER

I don't know python at all, but I do notice one difference in your map between your js and python:

mapTo(-1) // always emits -1

-- vs --

ops.map(lambda value: value - 1)  # emits interval index - 1

I think the solution is simple, just remove the "value":

ops.map(lambda value: -1)

However, if your "current value" is always -1 you can simplify by not using map at all and put -1 in your scan() function. Here's what it looks like in rxjs:

const countDown$ = interval(1000).pipe(
  scan(accumulator => accumulator - 1, 10)
  takeWhile(value => value >= 0)
);