Skip to content

Instantly share code, notes, and snippets.

@deebloo
Last active January 28, 2019 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deebloo/a2650cc636b1979b04fe6f4f9f903bf1 to your computer and use it in GitHub Desktop.
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)
);
}
}
@markwhitfeld
Copy link

Nothing can subscribe to this, so what is the reason for this code?

res.pipe(
      switchMapTo(this.value),
      take(1)
    );

Unless it was supposed to be returned?

@deebloo
Copy link
Author

deebloo commented Jan 28, 2019

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