3

I am using a library which needs to be cleaned up at exit time (i.e. closing a socket so that it does not hang until some timeout) in an OpenFL 2.2.1 application.

However, I could not find any event which is called when I close the window with Alt+F4 or the closing button of the window.

How can I detect that the application is terminating, in order to clean my resources?

madprog
  • 275
  • 1
  • 4
  • 13

2 Answers2

4

To answer your question about openfl-next, there is the lime.app.Application.onExit event, which it inherits from lime.app.Module. An Application reference is stored in openfl.display.Stage.application instance field.

So, a multi-version variant of the function would be as following:

static function setExitHandler(func:Void->Void):Void {
    #if openfl_legacy
    openfl.Lib.current.stage.onQuit = function() {
        func();
        openfl.Lib.close();
    };
    #else
    openfl.Lib.current.stage.application.onExit.add(function(code) {
        func();
    });
    #end
}

And then you would just

setExitHandler(function() {
    trace("Quit!");
});
YellowAfterlife
  • 2,043
  • 1
  • 13
  • 23
  • Was "next" at the time now lime 2.9.0? – Kev Feb 22 '16 at 18:02
  • 1
    Versions as of the time of writing were OpenFL 3.5.x/Lime 2.8.x. In the current versions, "next" is the default backend, while "legacy" is the older version of it that can be enabled via a flag (openfl_legacy) for compatibility purposes. – YellowAfterlife Feb 23 '16 at 19:32
0

Part of an answer would be to fallback to legacy OpenFL (with -Dopenfl-legacy or <haxedef name="openfl-legacy" />).

This trick forces the compiler into using the former API, which enables Lib.stage.onQuit.

public static function main():Void
{
    // …
    Lib.stage.onQuit = onClose;
    // …
}

private static function onClose()
{
    // …
    // Cleanup of opened resources
    // …
    Lib.close();
}

Be sure to call Lib.close() or your window won't be closeable any more!

However, this does not answer my question for the newer openfl-next.

madprog
  • 275
  • 1
  • 4
  • 13