Skip to content

Instantly share code, notes, and snippets.

@deebloo
Last active January 28, 2019 12:19
Show Gist options
  • Select an option

  • Save deebloo/a2650cc636b1979b04fe6f4f9f903bf1 to your computer and use it in GitHub Desktop.

Select an option

Save deebloo/a2650cc636b1979b04fe6f4f9f903bf1 to your computer and use it in GitHub Desktop.
Wrapping a state manager to allow for async actions
export type StateChange<A> = A | Observable<A> | Promise<A>;
const stateChangeToObservable = <A>(result: StateChange<A>): Observable<A> => {
if (isObservable(result)) {
return result;
} else if (result instanceof Promise) {
return from(result);
}
return of(result);
};
export class StateContainer<A, T> {
constructor(
private readonly dispatch: (action: A) => any,
public readonly value: Observable<T>\
) {}
update(src: StateChange<A>): Observable<T> {
const res = stateChangeToObservable(src).pipe(shareReplay(1));
res.subscribe(action => {
this.dispatch(action)
});
return res.pipe(
switchMapTo(this.value),
take(1)
);
}
}
@deebloo

deebloo commented Jan 28, 2019

Copy link
Copy Markdown
Author

Yeah was supposed to be returned. I've been writing to much rust

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment