zigar.function.Generator(T, allocating).yield(self, value) - chung-leong/zigar GitHub Wiki
Send a value or error to the JavaScript side through the async generator interface. A value of
null indicates the end of content generation. If the function returns false, the
for async (...) loop on the JavaScript been interrupted and no more values should be sent.
Usage:
const std = @import("std");
const zigar = @import("zigar");
const Generator = zigar.function.Generator(?error{OutOfMemory}![]u8);
pub fn start() !void {
try zigar.thread.use();
}
pub fn stop() void {
zigar.thread.end();
}
pub fn getStrings(a: std.mem.Allocator, generator: Generator) !void {
const thread = try std.Thread.spawn(.{}, generateStrings, .{ a, generator });
thread.detach();
}
fn generateStrings(a: std.mem.Allocator, generator: Generator) void {
for (0..10) |i| {
std.debug.print("generating item {d}\n", .{i});
if (!generator.yield(std.fmt.allocPrint(a, "string {d}", .{i}))) break;
} else generator.end();
}
import { getStrings, start, stop } from './generator-example-2.zig';
try {
start();
for await (const s of getStrings()) {
console.log(s.string);
break;
}
} finally {
console.log('finally');
stop();
}
generating item 0
string 0
generating item 1
finally
Arguments:
self:@This()value:T
Return value:
bool