Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

onClose may not be called for eagely initialized instances if override happens #2001

Open
shchuko opened this issue Sep 25, 2024 · 0 comments

Comments

@shchuko
Copy link

shchuko commented Sep 25, 2024

Describe the bug
onClose may not be called for eagely initialized instances if override happens

To Reproduce

Run this code:

package org.example

import org.koin.core.context.GlobalContext.startKoin
import org.koin.core.context.stopKoin
import org.koin.dsl.module
import org.koin.dsl.onClose
import org.koin.java.KoinJavaComponent.getKoin


class MyClass(val name: String) {
    init {
        println("Initializing '$name', allocating resources")
    }

    fun cleanup() {
        println("Cleaning up '$name', releasing resources")
    }
}

fun main() {
    val overrideModule = module {
        single { MyClass("override") } onClose { it?.cleanup() }
    }

    val module = module {
        // eager initialization
        single(createdAtStart = true) { MyClass("original") } onClose { it?.cleanup() }
    }
    
    // override
    startKoin { modules(module, overrideModule) }

    val instance = getKoin().get<MyClass>()
    println("Accessing '${instance.name}'")

    stopKoin()
    println("Koin stopped")
}

See output:

Initializing 'original', allocating resources
Initializing 'override', allocating resources
Accessing 'override'
Cleaning up 'override', releasing resources
Koin stopped

Expected behavior
onClose is called for both 'original' and 'override' instances. (Cleaning up 'original', releasing resources is printed too)

Actual behavior
onClose is called only for 'override' instance, possible leak.

Koin module and version:
koin-core:4.0.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant