Skip to content

Commit

Permalink
feat: create tick in a more reactive style
Browse files Browse the repository at this point in the history
  • Loading branch information
johannesjo committed Nov 6, 2018
1 parent ca34f75 commit 91329fc
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 26 deletions.
6 changes: 2 additions & 4 deletions src/app/core/time-tracking/time-tracking.module.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TimeTrackingService } from './time-tracking.service';
import { DialogIdleComponent } from './dialog-idle/dialog-idle.component';

@NgModule({
imports: [
CommonModule
],
declarations: [],
declarations: [DialogIdleComponent],
providers: [
TimeTrackingService
]
})
export class TimeTrackingModule {
constructor(private readonly _timeTrackingService: TimeTrackingService) {
this._timeTrackingService.init();
}
}
39 changes: 17 additions & 22 deletions src/app/core/time-tracking/time-tracking.service.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,30 @@
import { Injectable } from '@angular/core';
import * as moment from 'moment';
import { TRACKING_INTERVAL, WORKLOG_DATE_STR_FORMAT } from '../../app.constants';
import { BehaviorSubject } from 'rxjs';
import { interval, Observable } from 'rxjs';
import { map, share } from 'rxjs/operators';
import { Tick } from './time-tracking';

@Injectable({
providedIn: 'root'
})
export class TimeTrackingService {
public tick$: BehaviorSubject<Tick> = new BehaviorSubject({
duration: 0,
date: moment().format(WORKLOG_DATE_STR_FORMAT)
});
private _currentTrackingStart: number;
public tick$: Observable<Tick> = interval(TRACKING_INTERVAL).pipe(
map(() => {
const delta = Date.now() - this._currentTrackingStart;
this._currentTrackingStart = Date.now();
return {
duration: delta,
date: moment().format(WORKLOG_DATE_STR_FORMAT)
};
}),
// important because we want the same interval for everyone
share()
);

init() {
this.initPoll();
}

initPoll() {
let currentTrackingStart = moment();

setInterval(() => {
const now = moment();
const realPeriodDuration = moment.duration(now.diff(currentTrackingStart))
.asMilliseconds();
this.tick$.next({
duration: realPeriodDuration,
date: now.format(WORKLOG_DATE_STR_FORMAT)
});
// set to now
currentTrackingStart = moment();
}, TRACKING_INTERVAL);
constructor() {
this._currentTrackingStart = Date.now();
}
}

0 comments on commit 91329fc

Please sign in to comment.