From 3efa4b3579e6e0adfdbf95639ab8bbc830ea1763 Mon Sep 17 00:00:00 2001 From: Eric Erhardt Date: Wed, 30 Mar 2022 19:03:11 -0500 Subject: [PATCH] Move the background task logic into ShowsService, and only do it on first load. --- src/Mobile/Services/ShowsService.cs | 21 ++++++++++++++++++++- src/Mobile/ViewModels/DiscoverViewModel.cs | 4 +--- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/Mobile/Services/ShowsService.cs b/src/Mobile/Services/ShowsService.cs index db17fa0..ab6ee6b 100644 --- a/src/Mobile/Services/ShowsService.cs +++ b/src/Mobile/Services/ShowsService.cs @@ -9,6 +9,7 @@ public class ShowsService { private readonly HttpClient httpClient; private readonly ListenLaterService listenLaterService; + private bool firstLoad = true; public ShowsService(ListenLaterService listenLaterService) { @@ -73,7 +74,25 @@ public class ShowsService return new Show(response, listenLaterService); } - private async Task TryGetAsync(string path) + private Task TryGetAsync(string path) + { + if (firstLoad) + { + firstLoad = false; + + // On first load, it takes a significant amount of time to initialize + // the ShowsService. For example, Connectivity.NetworkAccess, Barrel.Current.Get, + // and HttpClient all take time to initialize. + // + // Don't block the UI thread while doing this initialization, so the app starts faster. + // Instead, run the first TryGet in a background thread to unblock the UI during startup. + return Task.Run(() => TryGetImplementationAsync(path)); + } + + return TryGetImplementationAsync(path); + } + + private async Task TryGetImplementationAsync(string path) { var json = string.Empty; diff --git a/src/Mobile/ViewModels/DiscoverViewModel.cs b/src/Mobile/ViewModels/DiscoverViewModel.cs index d36f3d5..3960beb 100644 --- a/src/Mobile/ViewModels/DiscoverViewModel.cs +++ b/src/Mobile/ViewModels/DiscoverViewModel.cs @@ -49,9 +49,7 @@ public class DiscoverViewModel : BaseViewModel private async Task FetchAsync() { - // run GetShowsAsync in the background, so things get initialized in the background - // like checking the cache and the web request - var podcastsModels = await Task.Run(() => showsService.GetShowsAsync()); + var podcastsModels = await showsService.GetShowsAsync(); if (podcastsModels == null) {