Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unsubscribing from events in Blazor #14093

Closed
aL3891 opened this issue Sep 18, 2019 · 2 comments
Closed

Unsubscribing from events in Blazor #14093

aL3891 opened this issue Sep 18, 2019 · 2 comments

Comments

@aL3891
Copy link

aL3891 commented Sep 18, 2019

Hello, i'm fairly new to blazor so i'm sorry if this is an obvious question.
I'm wondering what the best practice if subscribing and unsubscribing to events from an injected service in a blazor component.

i have a ILogger service and a LogView component, in the component i subscribe to the event like this:

protected override void OnAfterRender(bool firstRender)
{
    if (firstRender)
    {
        Logger.NotifyLog += OnNotify;
    }
 ...
}

First of all, is that the "right" way to do it? (it seems to be from the examples i've seen), but secondly, where should i unsubscribe from the event? There is no Hide or Stop type method that i've seen that's called when the component should stop updating itself.

Or are the event subscriptions cleaned up some other way? i have a custom proxy thing that's using weakreferences for this purpose, but if i remember correctly from netFX, regular events do not work like that right?

@campersau
Copy link
Contributor

You can implement the IDisposable interface and unsubscribe there. It is called when the component is removed. https://docs.microsoft.com/en-us/aspnet/core/blazor/components?view=aspnetcore-3.0#component-disposal-with-idisposable
Async disposal is tracked here #9960

@aL3891
Copy link
Author

aL3891 commented Sep 18, 2019

aha, great, thanks!

@aL3891 aL3891 closed this as completed Sep 18, 2019
@ghost ghost locked as resolved and limited conversation to collaborators Dec 2, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants