InsertKoinIO / koin

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

Automatically destroy Closeable beans on shutdown #1790

Open alturkovic opened 7 months ago

alturkovic commented 7 months ago

Is your feature request related to a problem? Please describe. I have a lot of beans which implement the Closeable interface. It would be nice if koin could destroy these beans on shutdown automatically instead of having to use single { MyBean } onClose { it?.close() }

Describe the solution you'd like Have koin call close() on all Closeable beans on shutdown.

Describe alternatives you've considered Support a new callback when destroying beans so I could do something similar to:

startKoin {
  module {
    singleOf(::SomeBean)
    single { MyBean }
  }

  onClose {
    if (it is Closeable) {
        it.close()
    }
  }
}

Target Koin project core

marcellogalhardo commented 7 months ago

It seems you want all bindings that implement a Closeable interface to act as onClose { it?.close} automatically.

How would you differentiate a Closeable binding that is provided in Koin that (1) should be closeable by Koin onClose from (2) one that should not be closed by Koin, such as one associated with androidx ViewModel.addCloseable?

alturkovic commented 7 months ago

I have no experience on Android, I was comparing the behaviour of Closeable beans in Spring. When shutting down a Spring application, all beans implementing Closeable are being closed, like having an implicit onClose { it?.close} call. I have not encountered a scenario where I implemented a Closeable interface that was handled as a singleton that I did not want to be closed on shutdown, so I am not familiar with the Android handling :/

slipdef commented 5 months ago

Really need this feature too. Adding onClose callbacks manually is not sweet.

becmer commented 1 week ago

It seems you want all bindings that implement a Closeable interface to act as onClose { it?.close} automatically.

How would you differentiate a Closeable binding that is provided in Koin that (1) should be closeable by Koin onClose from (2) one that should not be closed by Koin, such as one associated with androidx ViewModel.addCloseable?

This is a very good point. What about a dedicated interface, let's say org.koin.core.Closeable, or maybe org.koin.core.Disposable? This way it would be an explicit intent.