Update context from promise + async iterator stream #5241
-
I'm trying to make an API call that returns a promise + async iterator and then iterate through the results updating the context as the stream comes in. I've tried fromPromise and fromObservable, but no luck so far. All of the examples observables I can find for XState are simplified to the point I'm not sure they're usable. Here's the demo: Possibly related to: Same question in Discord: |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I think this does the trick (TS playground): // @target: esnext
import { setup, fromPromise, ActorRef, Snapshot } from "xstate"; // types: 5.19.2
async function* createAsyncIterator() {
yield "Hello";
await new Promise((resolve) => setTimeout(resolve, 1000));
yield "World!";
await new Promise((resolve) => setTimeout(resolve, 1000));
yield "Async Iterators are cool!";
}
type ParentEvent = { type: "UPDATE_VALUE"; value: string };
setup({
types: {} as {
context: {
value: string;
};
events: ParentEvent;
},
actors: {
consumeAsyncIterator: fromPromise(
async ({
input: { parent },
}: {
input: { parent: ActorRef<Snapshot<unknown>, ParentEvent> };
}) => {
for await (const value of createAsyncIterator()) {
parent.send({ type: "UPDATE_VALUE", value });
}
},
),
},
}).createMachine({
context: {
value: "",
},
invoke: {
src: "consumeAsyncIterator",
input: ({ self }) => ({ parent: self }),
},
}); |
Beta Was this translation helpful? Give feedback.
I think this does the trick (TS playground):