import xs, {Stream} from 'xstream'; import concat from 'xstream/extra/concat'; import {MainFn, Reducer} from './types'; import {StateSource} from './StateSource'; import microtask from 'quicktask'; const schedule = microtask(); export type Omit = {[P in Exclude]: T[P]}; export type Forbid = Omit & {[P in K]?: never}; export type OSo = {[P in N]: StateSource}; export type OSi = {[P in N]: Stream>}; export type MainWithState< So extends OSo, Si extends OSi, T, N extends string > = MainFn, Omit>; export function withState< So extends OSo, Si extends OSi, T = any, N extends string = 'state' >(main: MainFn, name: N = 'state' as N): MainWithState { return function mainWithState(sources: Forbid): Omit { const reducerMimic$ = xs.create>(); const state$ = reducerMimic$ .fold((state, reducer) => reducer(state), void 0 as T | undefined) .drop(1); const innerSources: So = sources as any; innerSources[name] = new StateSource(state$, name); const sinks = main(innerSources); if (sinks[name]) { const stream$ = concat( xs.fromObservable>(sinks[name]), xs.never() ); stream$.subscribe({ next: i => schedule(() => reducerMimic$._n(i)), error: err => schedule(() => reducerMimic$._e(err)), complete: () => schedule(() => reducerMimic$._c()), }); } return sinks as any; }; }