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)
};
}
}
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With