MessagePipe icon indicating copy to clipboard operation
MessagePipe copied to clipboard

Subscription is called multiple times if you resubscribe at the same frame in async task

Open nicloay opened this issue 2 years ago • 1 comments

Message brocker use the following Publish method and here is how it take subscriber list handlers.GetValues() What happens is that I trigger the publisher (in my case from input) and then subscribe to the same event again

private ISubscriber<ButtonClickMsg> _testSubscriber; 
private async UniTask RunLoop()
{
    while (true)
    {
        await _testSubscriber.FirstAsync(default);
        Debug.Log(">> called 4 times instead of 1 <<");
    }
}

And never the less _testPublisher will be called once, you will see debug.log 4 times,

For the temporary solution I copy the subscriber array to another array, so new value will not be considered, but there are probably better ways of handling this

So in MessageBrocker.cs line 48 I have this

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Publish(TMessage message)
        {
            var array =  handlers.GetValues().ToArray(); // copy array here
            
            for (int i = 0; i < array.Length; i++)
            {
                array[i]?.Handle(message);
            }
        }

nicloay avatar Oct 08 '24 13:10 nicloay

same issue here, they did not fix it. I guess would have to delay a frame until they handle this.

huylqnothing avatar Oct 24 '24 02:10 huylqnothing

This issue is stale because it has been open 180 days with no activity. Remove stale label or comment or this will be closed in 30 days.

github-actions[bot] avatar Apr 23 '25 00:04 github-actions[bot]