forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
/
output_from_observable.ts
91 lines (82 loc) · 2.49 KB
/
output_from_observable.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
assertInInjectionContext,
DestroyRef,
inject,
OutputOptions,
OutputRef,
OutputRefSubscription,
ɵRuntimeError,
ɵRuntimeErrorCode,
} from '@angular/core';
import {Observable} from 'rxjs';
import {takeUntilDestroyed} from './take_until_destroyed';
/**
* Implementation of `OutputRef` that emits values from
* an RxJS observable source.
*
* @internal
*/
class OutputFromObservableRef<T> implements OutputRef<T> {
private destroyed = false;
destroyRef = inject(DestroyRef);
constructor(private source: Observable<T>) {
this.destroyRef.onDestroy(() => {
this.destroyed = true;
});
}
subscribe(callbackFn: (value: T) => void): OutputRefSubscription {
if (this.destroyed) {
throw new ɵRuntimeError(
ɵRuntimeErrorCode.OUTPUT_REF_DESTROYED,
ngDevMode &&
'Unexpected subscription to destroyed `OutputRef`. ' +
'The owning directive/component is destroyed.',
);
}
// Stop yielding more values when the directive/component is already destroyed.
const subscription = this.source.pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
next: (value) => callbackFn(value),
});
return {
unsubscribe: () => subscription.unsubscribe(),
};
}
}
/**
* Declares an Angular output that is using an RxJS observable as a source
* for events dispatched to parent subscribers.
*
* The behavior for an observable as source is defined as followed:
* 1. New values are forwarded to the Angular output (next notifications).
* 2. Errors notifications are not handled by Angular. You need to handle these manually.
* For example by using `catchError`.
* 3. Completion notifications stop the output from emitting new values.
*
* @usageNotes
* Initialize an output in your directive by declaring a
* class field and initializing it with the `outputFromObservable()` function.
*
* ```ts
* @Directive({..})
* export class MyDir {
* nameChange$ = <some-observable>;
* nameChange = outputFromObservable(this.nameChange$);
* }
* ```
*
* @developerPreview
*/
export function outputFromObservable<T>(
observable: Observable<T>,
opts?: OutputOptions,
): OutputRef<T> {
ngDevMode && assertInInjectionContext(outputFromObservable);
return new OutputFromObservableRef<T>(observable);
}