Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: yieldSame for async generators #778

Open
aralroca opened this issue Mar 2, 2025 · 0 comments
Open

Proposal: yieldSame for async generators #778

aralroca opened this issue Mar 2, 2025 · 0 comments
Labels
enhancement New feature or request

Comments

@aralroca
Copy link
Collaborator

aralroca commented Mar 2, 2025

When we do HTML streaming, currently, async generators are the last ones to control the chunks better and render streaming lists incrementally (see example). But if we want to show a title with the number of elements rendered in the list, which is updated in streaming, it is currently impossible to do easily.

import { Database } from "bun:sqlite";

const db = new Database("db.sqlite");

export default function MovieList() {
  return (
   <>
      <h2>Number of movies: {/* ??? */}</h2>
      <ul>
        <MovieItems />
      </ul>
   </>
  );
}

// Streaming HTML from SQLite query
async function* MovieItems() {
  for (const movie of db.query("SELECT title, year FROM movies")) {
    yield (
      <li>
        {movie.title} ({movie.year})
      </li>
    );
  }
}

Proposal: Add the yieldSame API to allow for the modification of the same chunk each time instead of increasing the number of chunks.

Example:

import { Database } from "bun:sqlite";

const db = new Database("db.sqlite");

export default function MovieList() {
  const movies = db.query("SELECT title, year FROM movies");

  return (
   <>
      <Title movies={movies} />
      <ul>
        <MovieItems movies={movies} />
      </ul>
   </>
  );
}

async function* Title({ movies }) {
  let i = 0;

  for (const movie of movies) {
    yield (
      <h2>
        Number of movies {++i}
      </h2>
    );
  }
}

// Modifying same chunk in Streaming HTML
Title.yieldSame = true;

// Streaming HTML from SQLite query
async function* MovieItems({ movies }) {
  for (const movie of movies) {
    yield (
      <li>
        {movie.title} ({movie.year})
      </li>
    );
  }
}
@aralroca aralroca added the enhancement New feature or request label Mar 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant