2024-01-20 20:39:12 -05:00
|
|
|
/*
|
2024-09-06 10:22:13 +02:00
|
|
|
Copyright 2024 New Vector Ltd.
|
2024-01-20 20:39:12 -05:00
|
|
|
|
2025-02-18 17:59:58 +00:00
|
|
|
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
2024-09-06 10:22:13 +02:00
|
|
|
Please see LICENSE in the repository root for full details.
|
2024-01-20 20:39:12 -05:00
|
|
|
*/
|
|
|
|
|
|
2025-06-18 17:14:21 -04:00
|
|
|
import { type Observable, Subject, takeUntil } from "rxjs";
|
2024-08-27 07:47:20 -04:00
|
|
|
|
|
|
|
|
type MonoTypeOperator = <T>(o: Observable<T>) => Observable<T>;
|
2024-01-20 20:39:12 -05:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* A scope which limits the execution lifetime of its bound Observables.
|
|
|
|
|
*/
|
|
|
|
|
export class ObservableScope {
|
2024-12-17 04:01:56 +00:00
|
|
|
private readonly ended$ = new Subject<void>();
|
2024-01-20 20:39:12 -05:00
|
|
|
|
2024-12-17 04:01:56 +00:00
|
|
|
private readonly bindImpl: MonoTypeOperator = takeUntil(this.ended$);
|
2024-08-27 07:47:20 -04:00
|
|
|
|
2024-01-20 20:39:12 -05:00
|
|
|
/**
|
|
|
|
|
* Binds an Observable to this scope, so that it completes when the scope
|
|
|
|
|
* ends.
|
|
|
|
|
*/
|
2024-08-27 07:47:20 -04:00
|
|
|
public bind(): MonoTypeOperator {
|
|
|
|
|
return this.bindImpl;
|
|
|
|
|
}
|
|
|
|
|
|
2024-01-20 20:39:12 -05:00
|
|
|
/**
|
|
|
|
|
* Ends the scope, causing any bound Observables to complete.
|
|
|
|
|
*/
|
|
|
|
|
public end(): void {
|
2024-12-17 04:01:56 +00:00
|
|
|
this.ended$.next();
|
|
|
|
|
this.ended$.complete();
|
2024-01-20 20:39:12 -05:00
|
|
|
}
|
|
|
|
|
}
|