Skip to content

Commit

Permalink
fix(observeOn): release action references on teardown
Browse files Browse the repository at this point in the history
  • Loading branch information
kwonoj authored and benlesh committed Aug 13, 2021
1 parent 99fefcb commit 321d205
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
34 changes: 31 additions & 3 deletions src/internal/operators/observeOn.ts
@@ -1,3 +1,6 @@
/** @prettier */
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { MonoTypeOperatorFunction, SchedulerLike } from '../types';
import { operate } from '../util/lift';
import { OperatorSubscriber } from './OperatorSubscriber';
Expand Down Expand Up @@ -55,13 +58,38 @@ import { OperatorSubscriber } from './OperatorSubscriber';
* notifications as the source Observable, but with provided scheduler.
*/
export function observeOn<T>(scheduler: SchedulerLike, delay: number = 0): MonoTypeOperatorFunction<T> {
function dispatch(sub: Subscriber<any>, act: () => void) {
const context: { subscription: Subscription | null; sync: boolean } = { sync: false, subscription: null };
context.subscription = scheduler.schedule(
(state) => {
act();
const { subscription } = state;
state.subscription = null;

if (subscription) {
subscription.unsubscribe();
sub.remove(subscription);
} else {
state.sync = true;
}
},
delay,
context
);

if (!context.sync) {
sub.add(context.subscription);
} else {
context.subscription.unsubscribe();
}
}
return operate((source, subscriber) => {
source.subscribe(
new OperatorSubscriber(
subscriber,
(value) => subscriber.add(scheduler.schedule(() => subscriber.next(value), delay)),
() => subscriber.add(scheduler.schedule(() => subscriber.complete(), delay)),
(err) => subscriber.add(scheduler.schedule(() => subscriber.error(err), delay))
(value) => dispatch(subscriber, () => subscriber.next(value)),
() => dispatch(subscriber, () => subscriber.complete()),
(err) => dispatch(subscriber, () => subscriber.error(err))
)
);
});
Expand Down
1 change: 1 addition & 0 deletions src/internal/types.ts
Expand Up @@ -180,6 +180,7 @@ export interface SubjectLike<T> extends Observer<T>, Subscribable<T> {}
/** SCHEDULER INTERFACES */

export interface SchedulerLike extends TimestampProvider {
schedule<T>(work: (this: SchedulerAction<T>, state: T) => void, delay: number, state: T): Subscription;
schedule<T>(work: (this: SchedulerAction<T>, state?: T) => void, delay?: number, state?: T): Subscription;
}

Expand Down

0 comments on commit 321d205

Please sign in to comment.