Gieta Laksmana
  • Blog
  • Profile
  • Projects
    • VR World Arcade
    • Punch For Fun
    • Spectrum
    • Dimension Battle
  • Resume

How to handle Application Exit event on PRISM 5

6/15/2016

0 Comments

 
A couple months ago, I encountered an issue in which I have to perform some cleanup on one of my ViewModel. I know that there's an OnExit() function on the Application class, but I didn't know how to let my VM know from here without causing some tight coupling between the Application class and my VM (which is not ideal).

I gave up trying to solve it since I couldn't found a viable solution back then, and always put this bug aside. Today I decided to spend the day fixing this issue, and I did, with a lot of help from the internet.

The solution was to use the EventAggregator in the PRISM 5 library

1. Make a singleton which contain the EventAggregator
// singleton event system 
public static class EventSystem
{
  public static IEventAggregator Instance
  {
    get
    {
      // ?? operator, return left if not null, otherwise, return right
      return m_Instance ?? (m_Instance = new EventAggregator());
    }
  }
  private static IEventAggregator m_Instance;
}
2. Create the Event to be broadcasted
public class ApplicationExitEvent : PubSubEvent<int>
{
}
3. Make my VM subscribe to the event
token = 
EventSystem.Instance.GetEvent<ApplicationExitEvent>().Subscribe(
  OnApplicationExit, 
  ThreadOption.PublisherThread
  );
The ThreadOption CANNOT be UIThread, I guess since the UI is closed there's no more UI Thread.
The token is used to unsubscribe from the event (not shown)

4. Broadcast the event from Application.OnExit
protected override void OnExit(ExitEventArgs e)
{
  // broadcast that we're exiting
  EventSystem.Instance.GetEvent<ApplicationExitEvent>().Publish(e.ApplicationExitCode);
}
I wonder if I would've solved this issue a lot sooner if I know about EventAggregator beforehand (I didnt know about it before I found someone else's blog trying to solve the same issue)

Links that helped me:
  • Richard Dutton's blog
  • Rachel Lim's blog
  • PRISM 5 Event Aggregator Quickstart
0 Comments



Leave a Reply.

    Archives

    September 2018
    August 2018
    July 2018
    September 2017
    July 2017
    November 2016
    October 2016
    September 2016
    June 2016
    May 2016
    March 2016

    Categories

    All
    Shenanigans
    Software Engineering
    Swift
    Vr
    Xcode

    RSS Feed

Powered by Create your own unique website with customizable templates.