Hello team, I am looking for some help regarding s...
# koin
c
Hello team, I am looking for some help regarding scopes and Composables. Here is a small demonstration of the problem I have. I have an application with multiple windows so I want to have component(in this example it is the
ViewModelDependencies
) that I want to scope to be a
singleton
within a single Window of my application. I am not sure how to approach it, I have tried to use a
rememberKoinModules(WindowModule)
on each window but the singleton is shared across both windows. I also tried to use
KoinScope<String>(UUID.random().toString()) {...}
and put the
rememberKoinModules(WindowModule)
inside the scope but the
ViewModelDependencies
was still a singleton across both scopes. 🤔 I assume I am doing something wrong and I am not understanding something about the scoping API. Would someone have an idea for how to approach this problem?
Copy code
internal val WindowModule = module {
    single {
        ViewModelDependencies() 
    }
    viewModel {
        WindowViewModel()
    }
}

class WindowViewModel(
    private val dependencies: ViewModelDependencies,
) : ViewModel() {...}

@Composable
fun WindowScreen(
    viewModel: WindowViewModel= koinViewModel(),
) {...}

fun main() = application {
    KoinApplication(
        application = {
            modules(...)
        }
    ) {
        Window(
            onCloseRequest = ::exitApplication,
            title = "Window 1",
        ) {
            WindowScreen()
        }
        Window(
            onCloseRequest = ::exitApplication,
            title = "Window 2",
        ) {
            WindowScreen()
        }
    }
}
I tried something like this but it did not work:
Copy code
fun main() = application {
    KoinApplication(
        application = {
            modules(...)
        }
    ) {
        Window(
            onCloseRequest = ::exitApplication,
            title = "Window 1",
        ) {
            KoinScope<Long>("Window1") {
                rememberKoinModules { WindowModule }
                WindowScreen()
            }
        }
        Window(
            onCloseRequest = ::exitApplication,
            title = "Window 2",
        ) {
            KoinScope<Long>("Window2") {
                rememberKoinModules { WindowModule }
                WindowScreen()
            }
        }
    }
Ok I figured out the problem. I was not understanding how scopes worked. I should have read more about scopes.