Is there any onClose event in OpenFL?

1k Views Asked by At

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?

2

There are 2 best solutions below

2
On BEST ANSWER

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!");
});
0
On

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.