Created
September 15, 2022 09:39
-
-
Save Sebosek/21135e6afb9edd266e7f7d568876abdc to your computer and use it in GitHub Desktop.
Type safe observable filter for RxJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { BehaviorSubject, filter, Observable, OperatorFunction, pipe, UnaryFunction } from "rxjs"; | |
| import { Injectable } from '@angular/core'; | |
| interface User { | |
| id: string; | |
| name: string; | |
| } | |
| export type Nullable<T> = T | null; | |
| export const defined = <T>(): UnaryFunction<Observable<Nullable<T>>, Observable<T>> => pipe( | |
| filter(Boolean) as OperatorFunction<Nullable<T>, T> | |
| ); | |
| @Injectable({ | |
| providedIn: 'root' | |
| }) | |
| export class UserService { | |
| private _logged = new BehaviorSubject<Nullable<User>>(null); | |
| public get logged(): Observable<User> { | |
| return this._logged.asObservable().pipe( | |
| defined(), | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment