Reputation: 896
Is there any alternative to javax.inject.Provider in koin?
To react to actions, I am injecting Commands to my activity. Command is a single-run object, for example WriteToFile.
In dagger I could make it like this:
class MainPresenter : Presenter() {
@Inject
lateinit var writeFile: Provider<WriteFileCommand>
fun onSaveClicked() {
writeFile.get().run()
}
}
in koin, when I try to use:
class MainPresenter : Presenter() {
lateinit var writeFile: Provider<WriteFileCommand> by inject()
fun onSaveClicked() {
writeFile.get().run()
}
}
My koin module:
val appModule = module {
factory { WriteFileCommand(get(), get()) }
factory { FileProvider() }
single { DataStore() }
}
Than I got error saying:
Can't create definition for 'Factory [name='WriteFileCommand',class='com.test.WriteFileCommand']' due to error : No compatible definition found. Check your module definition
I understand that I can call:
var command: WriteFileCommand = StandAloneContext.getKoin().koinContext.get()
command.run()
But It looks so cumbersome
Upvotes: 2
Views: 1229
Reputation: 39853
There's nothing like a provider directly. If you use inject
, you'll use a lazy delegate. If you use get
, you'll create a new instance you declared the dependency with a factory
. So get
is what you need in your case. Just let your MainPresenter
implement KoinComponent
and you'll be able to use get
directly:
class MainPresenter : Presenter(), KoinCompontent {
fun onSaveClicked() = get<WriteFileCommand>().run()
}
Upvotes: 2