Skip to content

Commit

Permalink
Hook up disposing events and remove listeners on dispose
Browse files Browse the repository at this point in the history
  • Loading branch information
cpiber committed Feb 24, 2023
1 parent 604e0d8 commit c978307
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions BlazorBarcodeScanner.ZXing.JS/BarcodeReader.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,9 @@ protected override async Task OnAfterRenderAsync(bool firstRender)

BarcodeReaderInterop.BarcodeReceived += ReceivedBarcodeText;
BarcodeReaderInterop.ErrorReceived += ReceivedErrorMessage;
BarcodeReaderInterop.DecodingStarted += DecodingStarted;
BarcodeReaderInterop.DecodingStopped += DecodingStopped;

if (StartCameraAutomatically && _videoInputDevices.Count > 0)
{
await _backend.SetVideoInputDevice(SelectedVideoInputId);
Expand All @@ -136,13 +139,18 @@ protected override async Task OnAfterRenderAsync(bool firstRender)
[Obsolete("Please use DisposeAsync")]
public void Dispose()
{
StopDecoding();
DisposeAsync();
}
public async ValueTask DisposeAsync()
{
try
{
await StopDecoding();

BarcodeReaderInterop.BarcodeReceived -= ReceivedBarcodeText;
BarcodeReaderInterop.ErrorReceived -= ReceivedErrorMessage;
BarcodeReaderInterop.DecodingStarted -= DecodingStarted;
BarcodeReaderInterop.DecodingStopped -= DecodingStopped;
}
catch (Exception ex)
{
Expand Down Expand Up @@ -170,7 +178,6 @@ public async Task StartDecoding()
var height = StreamHeight ?? 0;
await _backend.StartDecoding(_video, width, height);
SelectedVideoInputId = await _backend.GetVideoInputDevice();
IsDecoding = true;
StateHasChanged();
}

Expand Down Expand Up @@ -200,7 +207,6 @@ public async Task StopDecoding()
{
BarcodeReaderInterop.OnBarcodeReceived(string.Empty);
await _backend.StopDecoding();
IsDecoding = false;
StateHasChanged();
}

Expand Down Expand Up @@ -266,6 +272,17 @@ private async Task ReceivedErrorMessage(ErrorReceivedEventArgs args)
StateHasChanged();
}

private Task DecodingStarted(DecodingActionEventArgs _)
{
IsDecoding = true;
return Task.CompletedTask;
}
private Task DecodingStopped(DecodingActionEventArgs _)
{
IsDecoding = false;
return Task.CompletedTask;
}

protected async Task ChangeVideoInputSource(string deviceId)
{
SelectedVideoInputId = deviceId;
Expand Down

0 comments on commit c978307

Please sign in to comment.