Skip to content

Instantly share code, notes, and snippets.

@roubachof
Last active September 12, 2023 09:28
Show Gist options
  • Save roubachof/81fd7425e97ba36c479729d69d47e51f to your computer and use it in GitHub Desktop.
Save roubachof/81fd7425e97ba36c479729d69d47e51f to your computer and use it in GitHub Desktop.
Delayed view with factory
namespace Sharpnado.Lazy
{
using System;
using System.Threading.Tasks;
using Prism;
using Sharpnado.Tabs;
using Sharpnado.Tasks;
using Xamarin.Forms;
public class DelayedPodViewWithFactory : ALazyView, IActiveAware
{
private readonly Func<BasePodView> factory;
public ITaskMonitor<BasePodView> LoadingMonitor { get; private set; } = TaskMonitor<BasePodView>.NotStartedTask;
private bool isActive;
public DelayedPodViewWithFactory(Func<BasePodView> factory)
{
this.factory = factory;
this.UseActivityIndicator = true;
this.AccentColor = Color.White;
}
public int DelayInMilliseconds { get; set; } = 200;
public bool IsActive
{
get => this.isActive;
set
{
this.isActive = value;
this.RaiseIsActiveChanged();
this.TrySetContentActive();
}
}
public BasePodView PodView => this.Content as BasePodView;
public event EventHandler IsActiveChanged;
public override void LoadView()
{
Console.WriteLine($"{this.GetType().Name}: LoadView");
if (this.IsLoaded)
{
return;
}
this.LoadingMonitor = TaskMonitor<BasePodView>.Create(
async () =>
{
Console.WriteLine($"{this.GetType().Name}: awaiting delay");
await Task.Delay(this.DelayInMilliseconds);
if (this.IsLoaded)
{
return (BasePodView)this.Content;
}
this.IsLoaded = true;
Console.WriteLine($"{this.GetType().Name}: Running factory");
this.Content = await Task.Run(this.factory);
this.TrySetContentActive();
return (BasePodView)this.Content;
});
}
protected void RaiseIsActiveChanged()
{
this.IsActiveChanged?.Invoke(this, EventArgs.Empty);
}
private void TrySetContentActive()
{
if (this.PodView == null)
{
return;
}
this.PodView.IsActive = this.IsActive;
if (this.PodView.BindingContext is IActiveAware activeAwareContext)
{
activeAwareContext.IsActive = this.IsActive;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment