All Projects → hadashiA → UniTaskPubSub

hadashiA / UniTaskPubSub

Licence: MIT license
UniTask & IUniTaskAsyncEnumerable baseed pub/sub messaging. this is like the UniTask version of UniRx.MessageBroker.

Programming Languages

C#
18002 projects

Projects that are alternatives of or similar to UniTaskPubSub

talks
This repository exists to help organize and discuss new talks.
Stars: ✭ 19 (-68.85%)
Mutual labels:  event
gobroker
golang wrapper for all (to-be) kinds of message brokers
Stars: ✭ 15 (-75.41%)
Mutual labels:  messaging
chatcola
chatcola.com messaging server - self-host your messages without multi-domain nightmare!
Stars: ✭ 25 (-59.02%)
Mutual labels:  messaging
DevSoc21
Official website for DEVSOC 21, our annual flagship hackathon.
Stars: ✭ 15 (-75.41%)
Mutual labels:  event
evtx
C# based evtx parser with lots of extras
Stars: ✭ 162 (+165.57%)
Mutual labels:  event
super-mario-message
Display custom messages in a Super Mario Bros environment
Stars: ✭ 18 (-70.49%)
Mutual labels:  messaging
qpid-cpp
Mirror of Apache Qpid C++
Stars: ✭ 77 (+26.23%)
Mutual labels:  messaging
php-event-manager
PHP event manager. simple, fully functional event management dispatcher implementation. 简洁,功能完善的事件管理实现,支持快速的事件组注册,设置事件优先级,通配符事件的监听。
Stars: ✭ 25 (-59.02%)
Mutual labels:  event
numspy
A python module for sending free sms as well as finding details of mobile number via website Way2sms.
Stars: ✭ 57 (-6.56%)
Mutual labels:  messaging
vscode-dms
Direct Messages for VS Code
Stars: ✭ 88 (+44.26%)
Mutual labels:  messaging
Muni
Chat with Cloud Firestore
Stars: ✭ 22 (-63.93%)
Mutual labels:  messaging
qpid-python
Mirror of Apache Qpid Python
Stars: ✭ 15 (-75.41%)
Mutual labels:  messaging
dead-simple
💀💡 Dead simple PubSub and EventEmitter in JavaScript
Stars: ✭ 21 (-65.57%)
Mutual labels:  event
qpid-broker-j
Mirror of Apache Qpid Broker-J
Stars: ✭ 52 (-14.75%)
Mutual labels:  messaging
android-chat-tutorial
Sample apps for the Stream Chat Android SDK's official tutorial
Stars: ✭ 44 (-27.87%)
Mutual labels:  messaging
awesome-integration
A curated list of awesome system integration software and resources.
Stars: ✭ 117 (+91.8%)
Mutual labels:  messaging
gosd
A library for scheduling when to dispatch a message to a channel
Stars: ✭ 21 (-65.57%)
Mutual labels:  messaging
blaster
Web hooks for message queues
Stars: ✭ 14 (-77.05%)
Mutual labels:  messaging
Events
社区举办过的活动信息
Stars: ✭ 17 (-72.13%)
Mutual labels:  event
mnm-hammer
mnm implements TMTP protocol. Let Internet sites message members directly, instead of unreliable, insecure email. Contributors welcome! (Client)
Stars: ✭ 66 (+8.2%)
Mutual labels:  messaging

UniTaskPubSub

UniTask & IUniTaskAsyncEnumerable based pub/sub messaging. This is like the UniTask version of UniRx.MessageBroker.

Pub/Sub (Publish/Subscribe) pattern

In the Pub/Sub messaging model, the sender who creates and sends a message is called the publisher. The party receiving the message is called the subscriber.

  • Makes the sender and receiver loosely coupled, rather than the object directly calling the method.
  • It is possible to create multiple processes for a single message. In other words, the number of subscribers to a publisher is 1:N.

UniTask

UniTask is a library that brings fast and powerful async/await to the Unity world.

UniTaskPubSub uses UniTask and allows async/await for processing pub/sub messages.

Pub/Sub & Game archtecture

In game development, one event in the game often affects many factors and many objects. This is one of the reasons why game development is so complex. It is useful to make the sender and receiver loosely coupled by a Pub/sub messaging system.

Installation

Requirements

Install via UPM (using Git URL)

  1. Navigate to your project's Packages folder and open the manifest.json file.
  2. Add this line below the "dependencies": { line
    • "jp.hadashikick.unitaskpubsub": "https://github.com/hadashiA/UniTaskPubSub.git?path=Assets/UniTaskPubSub#0.10.0",
  3. UPM should now install the package.

Install manually (using .unitypackage)

  1. Download the .unitypackage from releases page.
  2. Open UniTaskPubSub.x.x.x.unitypackage

Usage

UniTask based pub/sub

struct FooMessage
{
    public int Id;
}
var messageBus = new AsyncMessageBus();

// Subscriber

messageBus.Subscribe<FooMessage>(async msg =>
{
    await DoSomething1Async(msg.Id);
});

messageBus.Subscribe<FooMessage>(async msg =>
{
    await DoSomething2Async(msg.Id);
});


// Publisher

// Await for all subscribers.
await messageBus.PublishAsync(new FooMessage { Id = 1 });

// After PublishAsync awaited, DoSomething1Async and DoSomething2Async have been completed.

You can also use AsyncMessageBus.Default instance, instead of new AsyncMessageBus().

Fire & forget

When using Publish(), do not wait for Subscriber.

messageBus.Publish(new FooMessage { Id = 1 });

CancellationToken

PublishAsync and Publish can be passed a cancellationToken. This can be used to cancel the process registered in the Subscriber.

messageBus.Subscribe<FooMessage>(async (msg, cancellationToken) =>
{
    // ...
    cancellationToken.ThrowIfCancellationRequested();
    // ...
});

await messageBus.PublishAsync(new FooMessage(), cancellationToken);

Subscription

Subscribe returns IDisposable. Disposing of this will unsubscribe.

var subscription = messageBus.Subscribe<FooMessage>(...);
subscription.Dispose();

The AddTo extension to UniTask is useful.

messageBus.Subscribe<FooMessage>(...)
    .AddTo(cancellationToken);

Filter

AsyncMessageBus can insert any preprocessing or postprocessing into publish. This feature is called a filter.

Filters can be used to do the following in one step

  • Insert logging.
  • Ignore certain messages
  • etc..

Examples:

// Add filter type
class LoggingFilter : IAsyncPublishFilter
{
    public async UniTask PublishFilterAsync<T>(
        T msg,
        CancellationToken cancellation,
        Func<T, CancellationToken, UniTask> next)
    {
        UnityEngine.Debug.Log($"Publish {msg.GetType()}");
        await next(msg, cancellation); // Processing all subscribers.
        UnityEngine.Debug.Log($"Invoked {msg.GetType()}");
    }
}

class IgnoreFilter : IAsyncPublishFilter
{
    public async UniTask PublishFilterAsync<T>(
        T msg,
        CancellationToken cancellation,
        Func<T, CancellationToken, UniTask> next)
    {
        if (msg is FooMessage foo)
        {
            if (msg.SomeCondition) 
            {
                UnityEngine.Debug.LogWarning($"Ignore {msg}")
                return;
            }
        }
        await next(msg, cancellation); // Processing all subscribers.
    }
}
// Create filter inserted MessageBus
var messageBus = new AsyncMessageBus(new IAsyncPublishFilter[]
{
    new LoggingFilter(),
    new IgnoreFilter(),
});

IUniTaskAsyncEnumerable based pub/sub

Required UniTask.Linq

AsyncEnumerableMessageBus can subscribe to a message as an async stream.

AsyncEnumerableMessageBus.Receive<TMessage> returns IUniTaskAsyncEnumerable. You can take full advantage of LINQ operations and Subscribe functions for IUniTaskAsyncEnumerable.

struct FooMessage
{
    public int Id;
}
using UniTaskPubSub;

var messageBus = new AsyncEnumerableMessageBus();

messageBus.Receive<FooMessage>()
    .Where(msg => msg.Id > 1)
    .Take(2)
    .Subscribe(async foo => 
    {
        await LoadAsync(foo.Id);
        await ...
        await ...        
    });
    
//     
    
messageBus.Publish(new FooMessage { Id = 1 });
messageBus.Publish(new FooMessage { Id = 2 });
messageBus.Publish(new FooMessage { Id = 3 });

You can also use AsyncEnumerableMessageBus.Default instance, instead of new AsyncEnumerableMessageBus().

In Unity 2020.2+ + C# 8, you can also use await foreach.

await foreach (var foo in messageBus.Receive<FooMessage>())
{
    // Do something
}

Author

@hadashiA

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].