I'm trying to implement a method that is running continually, as long as the app's window is active, if the window is minimized that method should stop.
I'm using an MVVM architecture.
In my code behind I have this method:
protected override void OnAppearing()
{
if (BindingContext is MainPageViewModel vm)
{
vm.Init();
}
}
I edited the life cycle events.
public partial class App : Application
{
public static bool activeWindow;
public App()
{
InitializeComponent();
MainPage = new AppShell();
}
protected override Window CreateWindow(IActivationState activationState)
{
Window window = base.CreateWindow(activationState);
window.Activated += (s, e) => { activeWindow = true; };
window.Deactivated += (s, e) => { activeWindow = false; };
return window;
}
In my view model:
public async void Init()
{
await RunInBackground(TimeSpan.FromSeconds(1));
}
async Task RunInBackground(TimeSpan timeSpan)
{
var periodicTimer = new PeriodicTimer(timeSpan);
while (await periodicTimer.WaitForNextTickAsync())
{
if (App.activeWindow == true)
{
//Run code
}
else
continue;
}
}
So, when my page is loaded the method starts and I use the bool variable depending in the life cycle state, activated or deactivated.
Is this good code and efficient? Or is the cancelation token a better way to go?
Thanks in advance.