Skip to content

Instantly share code, notes, and snippets.

@Sebosek
Created September 15, 2022 09:39
Show Gist options
  • Select an option

  • Save Sebosek/21135e6afb9edd266e7f7d568876abdc to your computer and use it in GitHub Desktop.

Select an option

Save Sebosek/21135e6afb9edd266e7f7d568876abdc to your computer and use it in GitHub Desktop.
Type safe observable filter for RxJS
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