add (un)subscribe function

This commit is contained in:
Avraham Sakal
2023-05-15 13:22:11 -04:00
parent aed7cbc9de
commit a3bb0f281c
5 changed files with 44 additions and 6 deletions
+23 -2
View File
@@ -43,11 +43,12 @@ export interface Interpreter_T {
context: any;
eventQueue:Array<Event_T>;
isTransitioning: boolean;
subscriptions: Record<string, SubscriptionCallbackFunction_T>
}
export function interpret(machine:Machine_T, options:{state?:string, context:any}) : Interpreter_T{
let {state, context} = options;
if(typeof state === 'undefined'){ state = machine.states[0].name; }
const interpreter = {machine, state, context, eventQueue:[], isTransitioning:false}
const interpreter = {machine, state, context, eventQueue:[], isTransitioning:false, subscriptions: {}}
send(interpreter, ['entry', null] );
return interpreter;
}
@@ -80,6 +81,8 @@ export function send(interpreter : Interpreter_T, event:Event_T){
processNextEvent(interpreter);
}
interpreter.isTransitioning = false;
// only run subscriptions here, once the machine's state has settled:
Object.values(interpreter.subscriptions).forEach((subscriptionCallbackFunction)=>{ subscriptionCallbackFunction(interpreter); });
}
}
export const enqueue = send;
@@ -102,6 +105,7 @@ function processNextEvent(interpreter:Interpreter_T){
});
// processing of `goto` must be last:
if(goto_ !== null){
send(interpreter, ['exit', null]);
interpreter.state = goto_.targetStateName;
send(interpreter, ['entry', null]);
}
@@ -126,5 +130,22 @@ function categorizeReactions(reactions:Array<Reaction_T>) : {sideEffects:Array<S
return {sideEffects, contextMutations, goto_};
}
export type SubscriptionCallbackFunction_T = (self:Interpreter_T)=>void;
let subscriptionId : number = 0;
export function subscribe(interpreter:Interpreter_T, callback:SubscriptionCallbackFunction_T){
subscriptionId++;
interpreter.subscriptions[subscriptionId.toString()] = callback;
return subscriptionId;
}
export function unsubscribe(interpreter:Interpreter_T, subscriptionId:string){
delete interpreter.subscriptions[subscriptionId.toString()];
}
export const Spawn = function(){};
export const Unspawn = function(){};
export const Unspawn = function(){};
/*
export function useMachine(machine, options){
return useMemo(()=>interpret(AppMachine, {context:{}}),[]);
}
*/