0

I have an object that looks like this: [{ timestamp: object }]
The timestamp is created timestamp = Date.now();

Now, I am looking for a way to create an Observable that emits the objects in the real sequence, i.e. when the time between entries is 200ms then it needs to wait 200ms, if it's 2.5 seconds then it needs to wait 2500ms.

I get the difference by subtracting the two adjacent index values from each other.

My code is here:

startReplay() {
  this.recordingRunning = true;
  const replayValues = this.recordedListeningValues;
  this.formObservable = Observable.create(function(observer) {
    let lastTs;
    Object.keys(replayValues).forEach(function(key) {
        observer.timer(Math.floor((Number(key) - lastTs) / 1000)).next(key, lastTs);
        lastTs = Number(key);
    });
  });
  var source = this.formObservable.subscribe(x => console.log(x));
}

It throws the error: observer.timer is not a function

At the moment, I am only trying to log the differences between the timestamps in seconds. Now, I want to emit it in the differences between the two timestamps.

5
  • 1
    onNext was used in RxJS 4, in RxJS 5 call next instead. Commented Aug 17, 2017 at 15:35
  • thanks a lot that solves one problem and it works. Commented Aug 17, 2017 at 15:37
  • Observable.interval - I guess this is used to create an observable emit periodically. Commented Aug 17, 2017 at 15:47
  • Yeah, I think I wouldn't be able to do this using timer, would I? Commented Aug 17, 2017 at 15:52
  • 1
    Observable.timer not observer.timer Commented Aug 17, 2017 at 19:37

1 Answer 1

1

You can use delayWhen operator. But you need to know the timestamp of the start of the recording so that you can calculate the time of each event relative to the start of the recording

const startOfRecording = ??? // Date.now() when recording started
const recordedValues = ???

// each time someone subscribes to this observable
// the recorded events will play back in "real time"
this.formObservable = Observable
    .from(Object.keys(replayValues))
    .delayWhen(key => Observable.timer(key - startOfRecording))
    .map(key => replayValues[key]);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I will give it a try tomorrow and report back. This looks promising.
Thank you, that works! How can I determine what the Observable does onComplete? I knew how to do it on Observer.
Add a .finally(() => console.log("done")) to the end

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.