Go: `defer` executing a last activity?

In the documentation of the Go SDK, I see the defer used to complete a session. But when not using sessions, can I also use defer to execute a last workflow activity.

Conceptually, I want to execute a cleanup activity no matter the outcome of the previous activities.

e.g.

defer workflow.ExecuteActivity(ctx, activities.Cleanup, tenant, application)

Yes, executing any workflow code including activities is supported in the defer.

You should be careful about context passed to ExecuteActivity as it can be already cancelled. So I recommend using a disconnected context created through workflow.NewDisconnectedContext in the cleanup code.

@maxim I moved the following line close to the top of my workflow implementation and added the new context:

cleanupCtx, _ := workflow.NewDisconnectedContext(ctx)
defer workflow.ExecuteActivity(cleanupCtx, activities.Cleanup, tenant, application).Get(cleanupCtx, &result)

Should the Get(cleanupCtx, &result) be appended? With this function chaining, I’m not sure what I am deferring.

defer is tricky and I wouldn’t rely on it to execute the code you posted correctly. I would change it to:

defer func() { 
   workflow.ExecuteActivity(cleanupCtx, activities.Cleanup, tenant, application).Get(cleanupCtx, &result)
}()

to be on the safe side.