0

I have been reading this code if I will replace scan with map I get can not get property "getTime" of undefined, why is it happening I assume that both operator takes an item emits from observable and apply some function on it

this.clock = Observable.merge(
        this.click$,
        Observable.interval(5000)
    )
        .startWith(new Date())
        .map((acc : Date)=> {
            const date = new Date(acc.getTime());
             date.setSeconds(date.getSeconds() + 1);
            return date;
        });
blackHawk
  • 6,047
  • 13
  • 57
  • 100

1 Answers1

0

Because you merge two streams into a single one. You will receive events from click$ or interval. In these cases, they aren't of type Date so you can use the getTime method.

The scan operator allows keeping a state between events. The map one simply converts an input into an output. In the case of the last one, you will receive the event itself...

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • What does it mean scan operator keeps a state between events – blackHawk Jul 04 '16 at 15:45
  • I assume that .startWith(new Date()) emitting a date object and map will receive it so getTime should be read on acc – blackHawk Jul 04 '16 at 15:46
  • Yes but it's only for the first event... So it will initialize the value received first by the scan callback. – Thierry Templier Jul 04 '16 at 15:54
  • What Im assuming that code will start execution from startwith operator this will emit a date object which will go to map function(actually there was scan operator instead of map i replaced just for sake of understanding) because its type of Date, it should read getTime() (but there is error can not read property) – blackHawk Jul 04 '16 at 16:07
  • and the merge operator merging existing subject observable and interval(I assume that interval is used only for delaying it to 5 sec) and this will received by map function on second iteration – blackHawk Jul 04 '16 at 16:11
  • Perhaps this link could help you to understand: https://gist.github.com/staltz/868e7e9bc2a7b8c1f754. – Thierry Templier Jul 04 '16 at 16:22
  • When you merge streams, the new / resulting stream will receive events from them... You will receive corresponding values within operator callbacks. With scan, you have an additional parameter to handle a kind of context across events. – Thierry Templier Jul 04 '16 at 16:24
  • Okay so with scan we will have a context that acc is of type Date otherwise threre will be no way to recognize this, e.g with map – blackHawk Jul 04 '16 at 16:41
  • It means that we have maintained the state of acc as Date object, M i right? – blackHawk Jul 04 '16 at 16:42