Composition in Postal.NET

Today I pushed a new feature of Postal.NET: composition. What is this? Well, think of it as (very) lightweight sagas; a subscription is only fired when a number of messages, with certain characteristics, have been received. Let’s see some examples.

First, the most basic one:

using (Postal

    .Box

    .When("channel1", "topic1")

    .And("channel2", "topic2")

    .Subscribe(env => Console.WriteLine(env.Data)))

{

    Postal.Box.Publish("channel1", "topic1", "Will not show");

    Postal.Box.Publish("channel2", "topic2", "Hello, World!");

}

Here, we wait for two messages to arrive, on two different channel/topic pairs. Only after the second does arrive do we trigger the subscriber action.

Next, a timed composition:

using (Postal

    .Box

    .When("channel1", "topic1")

    .And("channel2", "topic2")

    .InTime(TimeSpan.FromSeconds(5))

    .Subscribe(env => Console.WriteLine(env.Data)))

{

    Postal.Box.Publish("channel1", "topic1", "Will not show");

 

    Thread.Sleep(6 * 1000);

 

    Postal.Box.Publish("channel2", "topic2", "Will not show too");

}

Now we give our composition 5 seconds, from the first condition until the last one. Because we are waiting for slightly longer than that, the subscriber action will never get triggered.

Finally, a composition with conditions:

using (Postal

    .Box

    .When("channel1", "topic1", env => env.Data is int)

    .And("channel2", "topic2")

    .Subscribe(env => Console.WriteLine(env.Data)))

{

    Postal.Box.Publish("channel1", "topic1", 1);

    Postal.Box.Publish("channel2", "topic2", "Hello, World!");

}

On each of the steps, here represented by When and And, we can supply conditions, over an Envelope. If any of these conditions is not met, then the composition fails. Of course, we can add any number of conditions.

The Subscribe method must be called when we have all the conditions in place, and, as usual, it returns an IDisposable. When we want to cancel this subscription, we just dispose of it.

You can find the code in GitHub, under the PostalWhen.NET project. I will publish a Nuget package to go along with Postal.NET soon.

Hope you find this cool, as I did! Winking smile

Published by

Ricardo Peres

Technical Evangelist at Simplifydigital. Microsoft MVP.

Leave a Reply

Your email address will not be published. Required fields are marked *


*