63 lines
2.0 KiB
TypeScript
63 lines
2.0 KiB
TypeScript
|
// (C) Copyright 2015 Moodle Pty Ltd.
|
||
|
//
|
||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||
|
// you may not use this file except in compliance with the License.
|
||
|
// You may obtain a copy of the License at
|
||
|
//
|
||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||
|
//
|
||
|
// Unless required by applicable law or agreed to in writing, software
|
||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||
|
// See the License for the specific language governing permissions and
|
||
|
// limitations under the License.
|
||
|
|
||
|
import { FormControl } from '@angular/forms';
|
||
|
import { Observable, OperatorFunction } from 'rxjs';
|
||
|
import { filter } from 'rxjs/operators';
|
||
|
|
||
|
/**
|
||
|
* Create an observable that emits the current form control value.
|
||
|
*
|
||
|
* @param control Form control.
|
||
|
* @returns Form control value observable.
|
||
|
*/
|
||
|
export function formControlValue<T = unknown>(control: FormControl): Observable<T> {
|
||
|
return control.valueChanges.pipe(
|
||
|
startWithOnSubscribed(() => control.value),
|
||
|
filter(value => value !== null),
|
||
|
);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Observable operator that waits for a promise to resolve before emitting the result.
|
||
|
*
|
||
|
* @returns Operator.
|
||
|
*/
|
||
|
export function resolved<T>(): OperatorFunction<Promise<T>, T> {
|
||
|
return source => new Observable(subscriber => {
|
||
|
const subscription = source.subscribe(async promise => {
|
||
|
const value = await promise;
|
||
|
|
||
|
return subscriber.next(value);
|
||
|
});
|
||
|
|
||
|
return subscription;
|
||
|
});
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Same as the built-in startWith operator, but evaluates the starting value for each subscriber
|
||
|
* on subscription.
|
||
|
*
|
||
|
* @param onSubscribed Callback to calculate the starting value.
|
||
|
* @returns Operator.
|
||
|
*/
|
||
|
export function startWithOnSubscribed<T>(onSubscribed: () => T): OperatorFunction<T, T> {
|
||
|
return source => new Observable(subscriber => {
|
||
|
subscriber.next(onSubscribed());
|
||
|
|
||
|
return source.subscribe(value => subscriber.next(value));
|
||
|
});
|
||
|
}
|