Skip to content

Event Subscribers ​

A subscriber reacts to one typed event. Add a subscriber to the photo save event that logs the ID of the saved record.

Generate a Subscriber ​

First generate SavedEvent in the photos package and add its payload as shown in Events. From the Project root, run the matching subscriber generator.

bash
forj make:subscriber photos:saved --no-open

GoForj creates internal/photos/saved_subscriber.go and registers the constructor and its handler in app/wire/inject_subscribers_app.go. For an additional App, the App-owned injector lives under app/<name>/wire/. See make:subscriber for the complete generated registration and removal options.

The generator subscribes on the default bus. Use --bus audit for a configured named bus such as audit, and publish to that same bus.

Add "log" to the imports in saved_subscriber.go and replace Handle.

go
// Handle records the ID delivered by the App's photo event bus.
func (s *SavedSubscriber) Handle(_ context.Context, event SavedEvent) error {
	log.Printf("photos.saved id=%d", event.PhotoID)
	return nil
}

Dispatch Durable Follow-up Work ​

For a reaction that needs retries, inject a job into the subscriber. In the photos package, a subscriber can give the saved ID to the CheckJob with its typed payload.

go
return s.checkJob.Queue(context.WithoutCancel(ctx), CheckJobPayload{PhotoID: event.PhotoID})

The example assumes checkJob *CheckJob is a constructor dependency. Detaching the handler cancellation lets accepted work continue in the local queue after the publisher returns. Use a durable queue backend when the work must survive a process restart.

Registration Timing ​

Wire constructs the subscriber and registers its handler before the event runtime starts. Place manual subscriptions in the App-owned injector beside the generated entries. Event values are created by the publisher when it has a fact to send.

Error Handling ​

Return a dependency error so the configured bus can report the outcome. Subscriber error behavior depends on the driver. Put retryable work in a job and make repeated delivery safe for the operation it performs.

Test the Reaction ​

Finish publishing from the photo service, then run forj dev. Save a photo and compare the id in the HTTP response with the photos.saved id=… line in the App terminal. This verifies the generated registration and the in-process bus together.

Test a subscriber's handler directly for its own dependency failures. For a distributed bus, send a test event across the deployed publisher and subscriber processes and verify the topic and outcome. See Event Tests.

Good Uses ​

Use subscribers for reactions that can run independently, such as recording an audit fact, updating a derived view, or asking a queue worker to do follow-up work. Keep the workflow that must complete before the response in the service that owns it.

Next Steps ​