The JVM SDK currently only supports legacy versions of Nitric prior to v1. This version is maintained for compatibility with existing projects and not recommended for new projects. New projects should be started using a supported SDK (presented automatically using the `nitric new` command) orget in touch to request an update to the latest version.
JVM - topic.subscribe()
Subscribe a handler to a topic and receive new events for processing.
import io.nitric.Nitric;
public class Application {
public static void main(String[] args) {
var topic = Nitric.INSTANCE.topic("new-user");
topic.subscribe(ctx -> {
// process event
return ctx;
});
Nitric.INSTANCE.run();
}
}
Parameters
- Name
middleware
- Required
- Required
- Type
- Middleware<EventContext> or List<Middleware<EventContext>>
- Description
The middleware (code) to be triggered by the topic.
Examples
Subscribe to a topic
import io.nitric.Nitric;
public class Application {
public static void main(String[] args) {
var topic = Nitric.INSTANCE.topic("new-user");
topic.subscribe(ctx -> {
// process event
return ctx;
});
Nitric.INSTANCE.run();
}
}
Subscibe to a topic with chained middleware
import io.nitric.Nitric;
public class Application {
public static void main(String[] args) {
var topic = Nitric.INSTANCE.topic("topic");
topic.subscribe(List.of((ctx, next) -> {
// process event
return next.invoke(ctx);
}, (ctx, next) -> {
// process event
return next.invoke(ctx);
}));
Nitric.INSTANCE.run();
}
}
Notes
- A function may only subscribe to a topic once, if multiple subscribers are required, create them in different functions.
- A function may subscribe to OR publish to a topic but not both