Hello! I’m developing an App for iOS and Android w...
# multiplatform
o
Hello! I’m developing an App for iOS and Android with Compose Multiplatform and need some way to cleanup resources (e.g. database connection) when the App exits. Lifecycle does not seem to handle this complete exit either forced by the user or by OS. Thank you for your help!
f
Why not using DisposableEffect on the root of your compose App?
o
I already tried something like:
Copy code
@Composable
fun ComposableExithandler() {
    println("App started")
    DisposableEffect(Unit) {
        onDispose {
            println("App ended")
        }
    }
}
but it did not work (only “App started” was displayed).
c
Forced exit is forced. Your app just dies. It doesn't get a chance to execute any cleanup code. That's why the OS displays a warning that forced exit may make apps unstable (at least, Android does).
f
Inside you code, preferably in the swift side
Copy code
NotificationCenter.default.addObserver(forName: UIApplication.willTerminateNotification, object: nil, queue: nil) {
      print("willTerminateNotification \($0)")
    }
in case of crash, this notification won’t be called , of course
o
@CLOVIS I don’t meant this kind of forced exit (like kill -9), perhaps my wording was not clear enough. Users can (at least on iOS) quit (not just hide) an application and as @François mentioned on iOS you actually can do some cleanup then. I already did something with Swift, so I probably could implement something for iOS myself. But I have no idea about Android …
f
on android, you have something like this.
Copy code
class MainApplication : Application() {

    override fun onTerminate() {
        super.onTerminate()
    }
}
Update/Add a Application class to your app
in the manifest.xml
Copy code
<application
    android:name=".MainApplication"
    ....
o
Ok, thank you @François, I will give it a try …
f
Oh my bad, onTerminate is not the good one
o
onDestroy
sounds good 😀.
f
yes me too 😄
One last things, your cleanup must be real quick, long cleanup need to enable background feature.