1
>
/*---------------------------------------------------------------------------------------------
reducer.ts
2
>
* Copyright (c) Microsoft Corporation. All rights reserved.
3
>
* Licensed under the MIT License. See License.txt in the project root for license information.
4
>
*--------------------------------------------------------------------------------------------*/
5
>
6
>
import { EqualityComparer, strictEquals, BugIndicatingError } from '../commonFacade/deps.js';
7
>
import { IObservable, IObservableWithChange, ISettableObservable } from '../base.js';
8
>
import { subtransaction } from '../transaction.js';
9
>
import { IChangeTracker } from '../changeTracker.js';
10
>
import { DebugNameData, DebugOwner } from '../debugName.js';
11
>
import { DerivedWithSetter, IDerivedReader } from '../observables/derivedImpl.js';
12
>
import { DebugLocation } from '../debugLocation.js';
13
>
14
>
export interface IReducerOptions<T, TChangeSummary = void, TOutChange = void> {
15
>
/**
16
>
* Is called to create the initial value of the observable when it becomes observed.
17
>
*/
18
>
initial: T | (() => T);
19
>
20
>
/**
21
>
* Is called to dispose the observable value when it is no longer observed.
22
>
*/
23
>
disposeFinal?(value: T): void;
24
>
changeTracker?: IChangeTracker<TChangeSummary>;
25
>
equalityComparer?: EqualityComparer<T>;
26
>
27
>
/**
28
>
* Applies the changes to the value.
29
>
* Use `reader.reportChange` to report change details or to report a change if the same value is returned.
30
>
*/
31
>
update(reader: IDerivedReader<TOutChange>, previousValue: T, changes: TChangeSummary): T;
32
>
}
33
>
34
>
/**
35
>
* Creates an observable value that is based on values and changes from other observables.
36
>
* Additionally, a reducer can report how that state changed.
37
>
*/
38
>
export function observableReducer<T, TInChanges, TOutChange = void>(owner: DebugOwner, options: IReducerOptions<T, TInChanges, TOutChange>): SimplifyObservableWithChange<T, TOutChange> {
39
// eslint-disable-next-line local/code-no-any-casts
40
return observableReducerSettable<T, TInChanges, TOutChange>(owner, options) as any;
41
}
43
>
/**
44
>
* Creates an observable value that is based on values and changes from other observables.
45
>
* Additionally, a reducer can report how that state changed.
46
>
*/
47
>
export function observableReducerSettable<T, TInChanges, TOutChange = void>(owner: DebugOwner, options: IReducerOptions<T, TInChanges, TOutChange>): ISettableObservable<T, TOutChange> {
48
let prevValue: T | undefined = undefined;
49
let hasValue = false;