Generator based control flow goodness for Java, using promises, letting you write non-blocking code in a nice-ish way.
co@4.0.0 has been released, which now relies on promises.
The primary API change is how co() is invoked.
Before, co returned a "thunk", which you then called with a callback and optional arguments.
Now, co() returns a promise.
Co.co(Co.gen(y -> y.yield(CompletableFuture.completedFuture(true))))
.whenComplete((value, err) -> {
if (err != null) System.err.println(err);
else System.out.println(value);
});If you want to convert a co generator function into a regular function that returns a promise,
you now use Co.wrap(fn).
Co.Wrapped fn = Co.wrap(Co.gen(y -> y.yield(CompletableFuture.completedFuture(y.arg(0)))));
fn.apply(true).thenAccept(val -> {
});co requires Java 21 or newer. Java has no yield construct, so a generator
body runs on its own virtual thread (JEP 444) and suspends at each
yield until co resumes it. Generators are therefore as cheap to create as
they are in JavaScript, and never occupy a platform thread while suspended.
A promise is a CompletableFuture. Any value with a then method — a
CompletionStage, or a Thenable for foreign promise implementations — is
accepted wherever a promise is.
<dependency>
<groupId>com.github.tj</groupId>
<artifactId>co</artifactId>
<version>4.6.0</version>
</dependency>$ mvn verify
The test suite runs under mvn test, and mvn verify additionally writes a
JaCoCo coverage report to target/site/jacoco.
Any library that returns promises works well with co.
import co.Co;
Co.co(Co.gen(y -> {
// yield any promise
Object result = y.yield(CompletableFuture.completedFuture(true));
return result;
})).exceptionally(err -> onerror(err));
Co.co(Co.gen(y -> {
// resolve multiple promises in parallel
CompletableFuture<Object> a = CompletableFuture.completedFuture(1);
CompletableFuture<Object> b = CompletableFuture.completedFuture(2);
CompletableFuture<Object> c = CompletableFuture.completedFuture(3);
Object res = y.yield(List.of(a, b, c));
System.out.println(res);
// => [1, 2, 3]
return null;
})).exceptionally(err -> onerror(err));
// errors can be caught
Co.co(Co.gen(y -> {
try {
y.yield(CompletableFuture.failedFuture(new RuntimeException("boom")));
} catch (Throwable err) {
System.err.println(err.getMessage()); // "boom"
}
return null;
})).exceptionally(err -> onerror(err));
static Object onerror(Throwable err) {
// log any uncaught errors
// co will not throw any errors you do not handle!!!
// HANDLE ALL YOUR ERRORS!!!
err.printStackTrace();
return null;
}The yieldable values currently supported are:
- promises —
CompletionStageandThenable - thunks —
ThunkandContextualThunk List(parallel execution)Map(parallel execution)- generators (delegation)
- generator functions (delegation)
Nested yieldable values are supported, meaning you can nest
promises within maps within lists, and so on!
A promise is a java.util.concurrent.CompletionStage. The reason a stage failed
with is unwrapped before it reaches the generator, so a body catches the
exception that was actually thrown rather than the CompletionException around
it.
Thunks are functions that only have a single argument, a callback.
A callback invoked with several values, as in done.done(null, stdout, stderr),
resolves to a List of them.
Thunk support only remains for backwards compatibility and may
be removed in future versions of co.
yielding a List will resolve all the yieldables in parallel.
Co.co(Co.gen(y -> {
Object res = y.yield(List.of(
CompletableFuture.completedFuture(1),
CompletableFuture.completedFuture(2),
CompletableFuture.completedFuture(3)));
System.out.println(res); // => [1, 2, 3]
return null;
})).exceptionally(err -> onerror(err));Just like lists, maps resolve all yieldables in parallel. The result keeps the
iteration order of the map you yielded, whatever order its values resolved in.
Co.co(Co.gen(y -> {
Map<String, Object> yielded = new LinkedHashMap<>();
yielded.put("1", CompletableFuture.completedFuture(1));
yielded.put("2", CompletableFuture.completedFuture(2));
Object res = y.yield(yielded);
System.out.println(res); // => {1=1, 2=2}
return null;
})).exceptionally(err -> onerror(err));Any generator or generator function you can pass into co
can be yielded as well. This should generally be avoided
as we should be moving towards spec-compliant promises instead.
Returns a promise that resolves a generator, generator function,
or any Fn that returns a value or a promise.
Co.co(Co.gen(y -> y.yield(CompletableFuture.completedFuture(true))))
.whenComplete((val, err) -> {
if (err != null) System.err.println(err);
else System.out.println(val);
});The same, with an explicit context. The context stands in for JavaScript's
this: a generator body reads it through y.context(), a thunk through
ContextualThunk, and everything the generator yields inherits it.
Convert a generator function into a regular function that returns a promise.
Co.Wrapped fn = Co.wrap(Co.gen(y -> y.yield(CompletableFuture.completedFuture(y.arg(0)))));
fn.apply(true).thenAccept(val -> {
});fn.generatorFunction() exposes the generator function it was built from.
Co.gen builds a generator function from a body; Co.generator builds a single
generator, the counterpart of immediately invoking a generator function. A body
receives a Yield handle, which carries yield, context() and args().
GeneratorFunction work = Co.gen(y -> {
y.yield(sleep(50));
return "yay";
});MIT