Usage with RxJS #1452
-
Is there anyone who could provide a more thorough example of consuming an observable as an invoke src and assigning the resulting data using assign than the example on the XState docs site? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I believe that the example here is pretty complete: https://github.com/davidkpiano/xstate/blob/7f5dfe300221b44f2800baf089b2c722202127ee/docs/guides/actors.md#spawning-observables You’d only have to convert it to use invoke, probably smth like this would do it:
|
Beta Was this translation helpful? Give feedback.
-
You'll have to forward the information using an event: import { assign, createMachine } from 'xstate'
import {from } from 'rxjs'
import { map } from 'rxjs/operators'
const numbers$ = from([1, 2, 3, 4])
type MContext = { total: number }
type MEvent = { type: 'UPDATE', number: number }
const machine = createMachine<MContext, MEvent>({
initial: 'noop',
context: {
total: 0,
},
invoke: {
src: () => numbers$.pipe(map(number => ({ type: 'UPDATE', number}))),
},
on: {
UPDATE: {
actions: assign({ total: (ctx, evt) => ctx.total + evt.number })
}
},
states: {
noop: {
}
}
}) |
Beta Was this translation helpful? Give feedback.
You'll have to forward the information using an event: