3

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.

Steven
  • 166,672
  • 24
  • 332
  • 435
George O
  • 139
  • 1
  • 11

1 Answers1

3

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.

Emre Aktürk
  • 3,306
  • 2
  • 18
  • 30
  • thanks, and how does Koin knows when the Activity will need one ? does that means it won't be single instance ? – George O Aug 24 '20 at 20:12
  • I am not sure about it. You can check the documents about core concept, modules, scopes and injecting paramaters. https://doc.insert-koin.io/#/koin-core/modules – Emre Aktürk Aug 25 '20 at 05:54