Skip to content

Commit

Permalink
perf(signals): avoid unecessary observable conversions in rxMethod (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
markostanimirovic authored Jan 31, 2024
1 parent 330bf7c commit fa45d92
Showing 1 changed file with 15 additions and 12 deletions.
27 changes: 15 additions & 12 deletions modules/signals/rxjs-interop/src/rx-method.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import {
assertInInjectionContext,
DestroyRef,
effect,
inject,
Injector,
isSignal,
Signal,
} from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
import { isObservable, Observable, of, Subject, Unsubscribable } from 'rxjs';
import { isObservable, noop, Observable, Subject, Unsubscribable } from 'rxjs';

type RxMethodInput<Input> = Input | Observable<Input> | Signal<Input>;

Expand All @@ -30,20 +30,23 @@ export function rxMethod<Input>(
destroyRef.onDestroy(() => sourceSub.unsubscribe());

const rxMethodFn = (input: RxMethodInput<Input>) => {
let input$: Observable<Input>;

if (isSignal(input)) {
input$ = toObservable(input, { injector });
} else if (isObservable(input)) {
input$ = input;
} else {
input$ = of(input);
const watcher = effect(() => source$.next(input()), { injector });
const instanceSub = { unsubscribe: () => watcher.destroy() };
sourceSub.add(instanceSub);

return instanceSub;
}

const instanceSub = input$.subscribe((value) => source$.next(value));
sourceSub.add(instanceSub);
if (isObservable(input)) {
const instanceSub = input.subscribe((value) => source$.next(value));
sourceSub.add(instanceSub);

return instanceSub;
}

return instanceSub;
source$.next(input);
return { unsubscribe: noop };
};
rxMethodFn.unsubscribe = sourceSub.unsubscribe.bind(sourceSub);

Expand Down

0 comments on commit fa45d92

Please sign in to comment.