@inject BrowserDatabase Database @implements IAsyncDisposable @ChildContent @code { [Parameter] public RenderFragment? ChildContent { get; set; } /// /// Loads the page. The token is cancelled when the page tears down - the reader left, or the session is /// closing - before runs: a load still under way then fails on the context the /// teardown disposed, and has nobody left to report it to. /// [Parameter] public EventCallback OnReady { get; set; } [Parameter] public EventCallback OnTearDown { get; set; } private CancellationTokenSource? _loading; protected override async Task OnInitializedAsync() { // Every page is prerendered on the server first, where there is no browser to open a database in. // The page renders its static content there; the database opens once it runs in the browser. if (RendererInfo.IsInteractive is false) { return; } Database.BeforeSessionReset += TearDownAsync; Database.AfterSessionReset += ReadyAsync; // Opening raises AfterSessionReset, which runs ReadyAsync once for every subscriber; only // an already-open database needs the explicit call. if (Database.Database.IsOpen) { await ReadyAsync(); return; } try { await Database.EnsureSessionAsync(); } catch (Exception) { // No backend would take it, or the file it found is not a database. Nothing raised // AfterSessionReset, so the page loads anyway: its own open fails the same way and it shows // why where the reader is looking - rather than the whole page, the Database files page and // its delete button included, giving way to the error boundary. await ReadyAsync(); } } private async Task TearDownAsync() { _loading?.Cancel(); if (OnTearDown.HasDelegate) { await OnTearDown.InvokeAsync(); } } private async Task ReadyAsync() { var loading = _loading = new CancellationTokenSource(); if (OnReady.HasDelegate) { await OnReady.InvokeAsync(loading.Token); } } public async ValueTask DisposeAsync() { Database.BeforeSessionReset -= TearDownAsync; Database.AfterSessionReset -= ReadyAsync; await TearDownAsync(); } }