If heartbeat
is true
, the nullability warning over heartbeatTarget
should go away. I remember there was the MemberNotNullWhen attribute. How do I use it in this case in order to disable the nullability warning over heartbeatTarget
?
However, it won't compile due to typeof(heartbeat)
it should be something else but not sure what.
internal static IGraph<SourceShape<IFeedMessage>,NotUsed> CreateGraph<TMat>(
Source<string,TMat> publisher,
bool heartbeat = false,
[property: MemberNotNullWhen(true, typeof(heartbeat))]
IActorRef? heartbeatTarget = null,
ILoggingAdapter? log = null
)
{
var graph = GraphDsl.Create(builder =>
{
var origSource = builder.Add(publisher);
var filter = builder.Add(Flow.Create<string, string>().WhereNot(x => string.IsNullOrEmpty(x)));
var serializer = builder.Add(GdaxFeedFlows.JsonDeserializeFlow(log));
builder.From(origSource.Outlet).To(filter.Inlet);
builder.From(filter.Outlet).To(serializer.Inlet);
var emptyFilter = builder.Add(GdaxFeedFlows.FilterEmpty());
// add heartbeat detection capabilities if requested
if (heartbeat)
{
var heartbeatFilter = builder.Add(GdaxFeedFlows.FilterHeartbeats(heartbeatTarget));
builder.From(serializer.Outlet).To(heartbeatFilter.Inlet);
builder.From(heartbeatFilter.Outlet).To(emptyFilter.Inlet);
}
else
{
builder.From(serializer.Outlet).To(emptyFilter.Inlet);
}
return new SourceShape<IFeedMessage>(emptyFilter.Outlet);
});
return graph;
}
CodePudding user response:
MemberNotNullWhen
doesn't work like that. You are only allowed to attribute Methods and Properties with it which is why you put a [property:]
as a compiler workaround.
Null annotations is supposed to help with compile time null-ref exceptions, but I don't think any of the current annotations would help here. Even if heartbeat
is true
, the heartBeatTarget
could still be null since it's the callers responsibility to pass it in. You can't just assume it'll be true because you'll get a null ref.
I think you would be better off checking if it's not null at runtime.
Null check
// add heartbeat detection capabilities if requested
if (heartbeat && heartBeatTarget is not null)
{
var heartbeatFilter = builder.Add(GdaxFeedFlows.FilterHeartbeats(heartbeatTarget));
builder.From(serializer.Outlet).To(heartbeatFilter.Inlet);
builder.From(heartbeatFilter.Outlet).To(emptyFilter.Inlet);
}