import { of , OperatorFunction , pipe } from 'rxjs' ; import { catchError , map , startWith } from 'rxjs/operators' ; export class AsyncState < T , E = any > { res : T | undefined = undefined ; error : E | undefined = undefined ; loading = true ; success = false ; complete = false ; constructor ( state = { } ) { Object . assign ( this , state ) ; } } export function createAsyncState < T , E = any > ( state = { } ) { return new AsyncState ( state ) ; } export function createSyncState < T , E = any > ( res ) { return new AsyncState < T , E > ( { loading : false , complete : true , res , } ) ; } export function isSuccess < T > ( state ) { return state . success ; } export function hasError < T > ( state ) { return ! ! state . error ; } export function isComplete ( state ) { return state . complete ; } export function isLoading ( state ) { return state . loading ; } export function toAsyncState < T , E = any > ( ) { return pipe ( map ( ( res ) => { return new AsyncState < T , E > ( { res , loading : false , complete : true , success : true , } ) ; } ) , startWith ( new AsyncState < T , E > ( ) ) , catchError ( ( error ) => { return of ( new AsyncState < T , E > ( { error , loading : false , complete : true , } ) ) ; } ) ) ; }