Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SergeyBurlaka/0584bc3f4aa7eaf0aeb2601d59245ffa to your computer and use it in GitHub Desktop.
Save SergeyBurlaka/0584bc3f4aa7eaf0aeb2601d59245ffa to your computer and use it in GitHub Desktop.
Activity, Fragment & Service as KoinComponents
Activity, Fragment & Service are extended with the KoinComponents extension. You gain access to:
by inject() - lazy evaluated instance from Koin container
get() - eager fetch instance from Koin container
release() - release module’s instances from its path
getProperty()/setProperty() - get/set property
val androidModule = module {
// a factory of Presenter
factory { Presenter() }
}
class DetailActivity : AppCompatActivity() {
// Lazy injected Presenter instance
override val presenter : Presenter by inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ...
}
In any single, factory or scoped definition,
you can use injection parameters:
parameters that will be injected and used by your definition:
val presenter : Presenter by inject { parametersOf(view) }
class Presenter(val view : View)
val myModule = module {
single{ (view : View) -> Presenter(view) }
}
Loading after start
After Koin has been started with startKoin { } function,
it is possible to load extra definitions modules with the following function:
loadKoinModules(modules...)
val myModule = module {
// Will match type ServiceImp only
single { ServiceImp() }
// Will match type Service only
single { ServiceImp() as Service }
}
val myModule = module {
// Will match type ServiceImp only
single { ServiceImp() }
// Will match type Service only
single { ServiceImp() as Service }
}
module {
// declare a scope for MyActivity
scope(named<MyActivity>()) {
scoped { MyPresenter() }
}
}
class MyActivity : AppCompatActivity {
// get presenter from current scope
val presenter : MyPresenter by currentScope.inject()
}
class MyFragment : Fragment() {
override fun onViewCreated(...) {
// get Presenter instance from Activity's scope
val presenter : MyPresenter by lazy { activity?.currentScope.get() }
}
}
Taming the Android lifecycle
Android components are mainly managed by their lifecycle: we can’t directly instantiate an Activity nor a Fragment.
The system make all creation and management for us, and make callbacks on methods: onCreate, onStart…
That’s why we can’t describe our Activity/Fragment/Service in a Koin module
In the case of MVP architecture style, the Presenter is a short live component to help/support the UI.
The presenter must be created each time the screen is showing, and dropped once the screen is gone.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment