George O
George O

Reputation: 187

How to dynamically change a dependency?

I have an interface named CrmRepository from which I implemented two classes SuiteCrmRepository and OneCrmRepository which are data sources for my application.

I want to swap the dependency (data source) dynamically whenever the user login with a different account.

I used Koin to inject the repositories into the view model in constructor:

class ModuleViewModel(private var crmRepo: CrmRepository) :ViewModel() {}

and declare the module in koin like this:

fun provideCrmRepository(
): CrmRepository {
    return if (crmType == CrmType.SUITE) {
        SuiteCrmRepository()
    } else if (crmType == CrmType.ONE){
        OneCrmRepository()
    }
}

single {
    provideCrmRepository()
}

The problem is once the ModuleViewModel is created, a single instance of CrmRepository is created too, which can't be changed or created again when a new ModuleViewModel is created but after i changed the crmType variable.

Upvotes: 3

Views: 1939

Answers (1)

Emre Aktürk
Emre Aktürk

Reputation: 3346

You should use factory keyword instead of single.

we declare our MySimplePresenter class as factory to have a create a new instance each time our Activity will need one.

By using single keyword, Koin providing same instance of object.

Change the lines to;

factory {
   provideCrmRepository()
}

Another solution might be unload and load modules whenever crmType changed.

Upvotes: 3

Related Questions