MCPcopy Create free account
hub / github.com/deanrad/rxfx / thresholdToggle

Function thresholdToggle

operators/src/thresholdToggle.ts:26–69  ·  view source on GitHub ↗
(
  workCreator: (event: T) => ObservableInput<R>,
  threshold: number = 2,
  mapper?: (_: T, inner: R) => S
)

Source from the content-addressed store, hash-verified

24 * ```
25 */
26 export function thresholdToggle<T, R, S = R>(
27 workCreator: (event: T) => ObservableInput<R>,
28 threshold: number = 2,
29 mapper?: (_: T, inner: R) => S
30): OperatorFunction<T, S> {
31 type NewType = Observable<T>;
32
33 return function (source: NewType) {
34 return new Observable((notify) => {
35 let innerSub: Subscription | null;
36 let hitsTowardThreshold = 0;
37
38 return source.subscribe({
39 next(trigger) {
40 hitsTowardThreshold += 1;
41
42 if (hitsTowardThreshold >= threshold) {
43 if (!innerSub || innerSub?.closed) {
44 innerSub = from(workCreator(trigger)).subscribe({
45 next: (inner) => {
46 const result = (mapper ? mapper(trigger, inner) : inner) as S;
47 notify.next(result);
48 },
49 error: (e) => notify.error(e)
50 });
51 } else {
52 console.log(innerSub?.closed, hitsTowardThreshold);
53 innerSub.unsubscribe();
54 innerSub = null;
55 }
56
57 hitsTowardThreshold = 0;
58 }
59 },
60 error(e) {
61 notify.error(e);
62 },
63 complete() {
64 notify.complete();
65 }
66 });
67 });
68 };
69}

Callers 1

Calls 1

subscribeMethod · 0.80

Tested by

no test coverage detected