Function toGenerator

  • Returns an AsyncGenerator wrapper around Reactive. This allows values to be iterated over using a for await loop, like Chains.

    // Reactive numerical value
    const number = Reactive.number(10);

    const g = Reactive.toGenerator(number);
    for await (const v of g) {
    console.log(v); // Prints out whenever the reactive value changes
    }
    // Execution doesn't continue until Reactive finishes

    When/if source closes, an exception is thrown. To catch this, wrap the calling for await in a try-catch block

    try {
    for await (const v of g) {
    }
    } catch (error) {
    }
    // Completed

    Use something like setTimeout to loop over the generator without impeding the rest of your code flow. For example:

    // Listen for every pointerup event
    const ptr = Reactive.fromEvent(document.body, `pointerup`);
    // Start iterating
    setTimeout(async () => {
    const gen = Reactive.toGenerator(ptr);
    try {
    for await (const v of gen) {
    // Prints out whenever there is a click
    console.log(v);
    }
    } catch (e) { }
    console.log(`Iteration done`);
    });

    // Execution continues here immediately

    Type Parameters

    • V

    Parameters

    Returns AsyncGenerator<V>