InsertKoinIO / koin

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

Caching issue #336

Closed michaelbukachi closed 5 years ago

michaelbukachi commented 5 years ago

I don't know if I can categorise this as a bug or not? I do not have code to replicate it but I'll try to simplify the problem I'm facing. I have a background job (work manager) which fetches some data. All the dependencies being injected into this job need to be new instances, especially the ones for realm database since realm instances can be shared across threads. This works most of the time but occasionally it results in a crash. After setting up logging particularly in the constructor of the Repository being injected, I noticed that the constructor is not always called. These are the situations where it always crashes. Below is the basic of my repo:

class Repository constructor(realm: Realm) {
    init {
        Timber.i("Constructor touched")
    }
}

At first, I thought it was a constructor injection issue so I changed my code from using construction injection to the by inject method. This didn't work either. So basically, the Repository is occasionally reused producing undesirable behaviour. All Repositories and Realm are not singletons so there should be no reuse. Is this the default behaviour? Is there an explicit way of making sure that a new instance is provided?

Thanks in advance.

kldMohammed commented 5 years ago

Show your module definition , abd what exactly error that was printed out in the console

michaelbukachi commented 5 years ago

I solved it. I had made a silly mistake the previous night. This was the problem

Realm -> Factory
    v
Repository -> Factory
    v
OtherClass -> Singleton
    v
BackgroundWorker

The singleton instance of the OtherClass was causing the issue. Never commit before you sleep :sweat_smile: