Introduces Cache helper class.

This commit is contained in:
Henning Dieterichs 2022-02-18 18:45:12 +01:00
parent 3aafd130ec
commit bfda62fd81
No known key found for this signature in database
GPG key ID: 771381EFFDB9EC06

View file

@ -24,11 +24,6 @@ export interface IAudioCueService {
export class AudioCueService extends Disposable implements IAudioCueService { export class AudioCueService extends Disposable implements IAudioCueService {
readonly _serviceBrand: undefined; readonly _serviceBrand: undefined;
private readonly audioCueEnabledObservables = new Map<
AudioCue,
IObservable<boolean>
>();
private readonly screenReaderAttached = fromEvent( private readonly screenReaderAttached = fromEvent(
this.accessibilityService.onDidChangeScreenReaderOptimized, this.accessibilityService.onDidChangeScreenReaderOptimized,
() => this.accessibilityService.isScreenReaderOptimized() () => this.accessibilityService.isScreenReaderOptimized()
@ -65,27 +60,42 @@ export class AudioCueService extends Disposable implements IAudioCueService {
} }
} }
private readonly isEnabledCache = new Cache((cue: AudioCue) => {
const settingObservable = fromEvent(
Event.filter(this.configurationService.onDidChangeConfiguration, (e) =>
e.affectsConfiguration(cue.settingsKey)
),
() => this.configurationService.getValue<'on' | 'off' | 'auto'>(cue.settingsKey)
);
return new LazyDerived(reader => {
const setting = settingObservable.read(reader);
if (setting === 'auto') {
return this.screenReaderAttached.read(reader);
} else if (setting === 'on') {
return true;
}
return false;
}, 'audio cue enabled');
});
public isEnabled(cue: AudioCue): IObservable<boolean> { public isEnabled(cue: AudioCue): IObservable<boolean> {
let observable = this.audioCueEnabledObservables.get(cue); return this.isEnabledCache.get(cue);
if (!observable) { }
const settingObservable = fromEvent( }
Event.filter(this.configurationService.onDidChangeConfiguration, (e) =>
e.affectsConfiguration(cue.settingsKey) class Cache<TArg, TValue> {
), private readonly map = new Map<TArg, TValue>();
() => this.configurationService.getValue<'on' | 'off' | 'auto'>(cue.settingsKey) constructor(private readonly getValue: (value: TArg) => TValue) {
); }
observable = new LazyDerived(reader => {
const setting = settingObservable.read(reader); public get(arg: TArg): TValue {
if (setting === 'auto') { if (this.map.has(arg)) {
return this.screenReaderAttached.read(reader); return this.map.get(arg)!;
} else if (setting === 'on') {
return true;
}
return false;
}, 'audio cue enabled');
this.audioCueEnabledObservables.set(cue, observable);
} }
return observable;
const value = this.getValue(arg);
this.map.set(arg, value);
return value;
} }
} }