InsertKoinIO / koin

Koin - a pragmatic lightweight dependency injection framework for Kotlin & Kotlin Multiplatform
https://insert-koin.io
Apache License 2.0
8.76k stars 695 forks source link

KoinAppAlreadyStartedException after closing the app and relaunching it quickly #1864

Open armond-avanes opened 1 month ago

armond-avanes commented 1 month ago

Describe the bug I'm using Koin in my Compose Multiplatform project and trying to keep as much as possible in commonMain, so I'm using KoinApplication(...) in my top layer composable function.

When I close the app (Android) and relaunch it quickly, I get KoinAppAlreadyStartedException. I believe that when I close the app, the activity is destroyed but the app itself is still alive for a couple of more seconds... in that case, when I relaunch it quickly, the app itself is not reinitiated (already exists) but the activity is recreated (because it has been destroyed). When KoinApplication(...) is called and it detects that the Koin has already been started in the past, it throws the exception.

I know I can make use of KoinContext() and instead start the Koin in "Application.onCreate()" to fix this issue. But then I will need to repeat a similar logic for iOS and Desktop which is what I'm trying to avoid.

To Reproduce Steps to reproduce the behavior:

  1. Close the app
  2. Quickly relaunch it
  3. See error

Expected behavior KoinApplication should handle this situation gracefully.

Koin module and version:

Nek-12 commented 1 month ago

By starting Koin in composition you absolve yourself of any chance of injecting dependencies outside composition. The correct approach is to start Koin in the application and make a function in shared module that starts koin and call it from swift.

armond-avanes commented 1 month ago

@Nek-12 I understand your point, but KoinApplication() is a valid Koin [composable] API and it's not just a hacky way of doing things. If there is an API for something, it should work. Otherwise the API can be marked as deprecated, and the documentation should be updated to explain that there is no platform independent way to start Koin in Compose.