Usage with RxJS
The interpreted machine (i.e., service
) can be used as an event emitter. With RxJS, the fromEventPattern()
Observable creator can be used to turn the service
into an observable stream of currentState
objects:
import { Machine } from 'xstate';
import { interpret } from 'xstate/lib/interpreter';
import { fromEventPattern } from 'rxjs';
const machine = Machine({
/* machine definition */
});
const service = interpret(machine);
const state$ = fromEventPattern(callback => {
service.onTransition(callback);
});
state$.subscribe(state => {
// Logs the current state
console.log(state);
});
const event$ = // a stream of event objects
event$.subscribe(event => {
service.send('SOME_EVENT');
});