3

I have a ReplaySubject that accumulate data with scan operator and every 10000 ms should be reset. Is there any another way to do it?

Now:

let subject = new ReplaySubject();

subject.scan((acc, cur) => {
            acc.push(cur);
            return acc;
        }, [])
        .subscribe(events => {
            localStorage.setItem('data', JSON.stringify(events))
        });

subject
    .bufferTime(10000)
    .map(() => {
        subject.observers[0]._seed = [];
    })
    .subscribe(() => localStorage.removeItem('data'));
dariashka
  • 175
  • 1
  • 13

1 Answers1

4

I asked a very similar question few days ago and later answered myself

accumulating values such as with scan but with the possibility to reset the accumulator over time

maybe this can help you

SOME MORE DETAILS

An alternative approach is to have an Observable which acts as a timer which emits at a fixed interval, 10000ms in your case.

Once this timer emits, you pass the control to the Observable that cumululates via scan operator. To pass the control you use the switchMap operator to make sure the previous instance of the Observable completes.

If I understand correctly what you want to achieve, I would use a normal Subject rather than ReplaySubject.

The code could look something like this

const subject = new Subject<number>();

const timer = Observable.timer(0, 1000).take(4);

const obs = timer.switchMap(
    () => {
        console.log('-----');
        return subject
            .scan((acc, cur) => {
                acc.push(cur);
                return acc;
            }, []);
    }
)

obs.subscribe(
    events => {
        console.log(JSON.stringify(events))
    }
);


// TEST DATA EMITTED BY THE SUBJECT
setTimeout(() => {
    subject.next(1);
}, 100);
setTimeout(() => {
    subject.next(2);
}, 1100);
setTimeout(() => {
    subject.next(3);
}, 2100);
setTimeout(() => {
    subject.next(4);
}, 2200);
Picci
  • 16,775
  • 13
  • 70
  • 113