I'd like to understand context isolation a bit mor...
# koin
e
I'd like to understand context isolation a bit more. Here's a test:
Copy code
import org.koin.dsl.koinApplication
import org.koin.dsl.module
import org.koin.core.module.Module

class Foo

fun main() {
    val module = module { single<Foo> { Foo() } }
    val moduleFunc = { module { single<Foo> { Foo() } } }

    check(module, module)
    check(module, moduleFunc())
}

fun check(module1: Module, module2: Module) {
    val app1 = koinApplication { modules(module1) }
    val foo1 = app1.koin.get<Foo>()

    val app2 = koinApplication { modules(module2) }
    val foo2 = app2.koin.get<Foo>()

    if (app1.koin == app2.koin) {
        error("koin is the same")
    }

    if (foo1 == foo2) {
        println("same")
    } else {
        println("different")
    }
}

// output:
same
different
My understanding was that a module is defining the how, not the what, and because of that, if I pass the same module to two different koin applications, I'd expect to create a different instance for
single
, but it's not the case. How could I achieve that without creating a new module for each
koinApplication
?
p
so you want share memory between apps?
e
no I don't
but it seems it's shared. Unless I recreate the module per application
p
my very best guess is that you are initializing them twice
ca you try that but only having koinApplication { modules(module1) } and koinApplication { modules(module2) } in main ? and only then check
e
to make it clear, the ideal output of the test above is
Copy code
different
different
so if I inject the same module to two applications, the created instances are different. According to the test, in order to have that behaviour, one has to create a new instance of the module per koin application.
a
a module instance pre allocate some data, before being loaded.
but in your case, this seems to be legit. You have 2 differnt instanves of
Foo
e
no I don't. if you run the test, the output you'll see is
Copy code
same
different
I only get different instances of
Foo
when the modules themselves are different
a
yeah, ok. Seems link to metadata pre allocation
Koin context isolation is not directly intended with same module instance
OR ... you can use a function instead of val to declare your module and avoid your pre allocation
fun myModule() = module { ... }
e
yeah that's what I did as a workaround
it's just a bit counter-intuitive, I'd expect a module to define the how, like the structure of objects to be injected, and be reusable across koin applications (isolated)
1
a
you are in a special case to reuse definition modules, but not there metadata 🙂