Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closure can be eliminated: method has overload to avoid closure creation

JetBrains Rider suggests the following over Disposable.Create:

Closure can be eliminated: method has overload to avoid closure creation

How do I fix it?

public sealed class RedisSubscriber<TKey, TMessage> : IBusSubscriber<TKey, TMessage>
{
    private readonly IConnectionMultiplexer _connectionMultiplexer;
    private readonly IRedisSerializer _serializer;

    public RedisSubscriber(IConnectionMultiplexer connectionMultiplexer, IRedisSerializer serializer)
    {
        _connectionMultiplexer = connectionMultiplexer;
        _serializer = serializer;
    }

    public IObservable<RedisValue> SubscribeAsync(TKey key)
    {
        var channel = CreateChannel(key);
        var subscriber = _connectionMultiplexer.GetSubscriber();

        return Observable.Create<RedisValue>(observer =>
        {
            subscriber.SubscribeAsync(channel, (redisChannel, redisValue) =>
            {
                if (string.IsNullOrEmpty(redisValue))
                {
                    return;
                }

                observer.OnNext(redisValue);
            });
            return Disposable.Create(() => subscriber.Unsubscribe(channel));
        });
    }

    private RedisChannel CreateChannel(TKey key)
    {
        return key switch
        {
            string s => new RedisChannel(s, RedisChannel.PatternMode.Auto),
            byte[] v => new RedisChannel(v, RedisChannel.PatternMode.Auto),
            _ => new RedisChannel(_serializer.Serialize(key), RedisChannel.PatternMode.Literal)
        };
    }
}
like image 753
nop Avatar asked Dec 06 '25 15:12

nop


1 Answers

Disposable.Create has an overload with a signature of Disposable.Create(TState, Action<TState> action). This overload allows you to pass in your state. In your case, you are using subscriber and channel in your Disposable.Create method. If you don't pass in subscriber or channel to your delegate, it will create a closure to capture those references.

So in order to avoid a closure getting created, you need to use the overload as Rider suggests. To do that, you can do something along the lines of

Disposable.Create((subscriber, channel), x => x.subscriber.Unsubscribe(x.channel));
like image 136
JohanP Avatar answered Dec 08 '25 04:12

JohanP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!