The top-level view model will typically load data related to the logged-in user.
When the authentication service logs a user in, it makes their User
fact available via the UserProvider
.
Take a UserProvider
as a dependency in the view model.
Define a field to hold onto the UserProvider.Handler
.
In the Load
method, add a handler to the UserProvider
.
The handler returns a function that will be called to clean up.
In the Unload
method, remove the handler from the UserProvider
.
This will cause the cleanup function to be called.
The cleanup function will also be called when the user logs off.
public partial class SiteListViewModel : ObservableObject, ILifecycleManaged
{
private readonly JinagaClient jinagaClient;
private readonly UserProvider userProvider;
private UserProvider.Handler? handler;
public ObservableCollection<SiteHeaderViewModel> Sites { get; } = new();
public SiteListViewModel(JinagaClient jinagaClient, UserProvider userProvider)
{
this.jinagaClient = jinagaClient;
this.userProvider = userProvider;
}
public void Load()
{
handler = userProvider.AddHandler(user =>
{
var specification = Given<User>.Match((user, facts) =>
// ...
);
var observer = jinagaClient.Watch(specification, user, projection =>
{
// Update the Sites collection
});
return () =>
{
observer.Stop();
observer = null;
Sites.Clear();
};
});
}
public void Unload()
{
userProvider.RemoveHandler(handler);
handler = null;
}
}