Skip to content

NATS .NET v3.1.0

Latest

Choose a tag to compare

@mtmk mtmk released this 31 Jul 09:29
24159b4

NuGet

Minor release on top of 3.0.1. Adds subscription events with an OnSubscribed callback, enables full-graph NuGet dependency auditing, and adds documentation examples.

  • Add subscription events with OnSubscribed callback (#1217)
  • Audit transitive dependencies (#1220)
  • Add subject-dispatch serialization example (#1218)
  • Add docs.nats.io examples to main (#1216)

The async enumerable returned by SubscribeAsync does not establish the subscription until it is iterated. When the enumerable is handed off to another task, the new OnSubscribed callback signals when it is safe to publish messages the subscription must observe:

var subscribed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);

var opts = new NatsSubOpts
{
    Events = new NatsSubEvents
    {
        OnSubscribed = _ =>
        {
            subscribed.TrySetResult();
            return default;
        },
    },
};

var consumer = Task.Run(async () =>
{
    await foreach (var msg in nats.SubscribeAsync<string>("greet", opts: opts))
    {
        // process messages
    }
});

await subscribed.Task;
await nats.PublishAsync("greet", "hello"); // subscription is established

OnSubscribed fires once the SUB protocol message has been queued on the subscribing connection, which is enough when publishing on the same connection. If the publisher uses a different connection, add a PingAsync round-trip on the subscribing connection after the callback to be sure the server has processed the subscription:

await subscribed.Task;
await nats.PingAsync(); // server has processed the SUB
await otherConnection.PublishAsync("greet", "hello");

Thanks

  • @btzdnl for reporting the SubscribeAsync early-return issue and helping with the design (#1178)