🥥
Cokoin
Injection library for Compose (Multiplatform and Jetpack), Koin wrapper. It uses @Composable
functions to configure KoinContext
and Scopes
.
Installation
Library is hosted on Maven Central. Add following the package to your module build.gradle.kts
:
dependencies {
// for JetBrains' Compose Multiplatform
implementation("dev.burnoo:cokoin:0.1.5")
// for Google's Jetpack Compose
implementation("dev.burnoo:cokoin-jetpack:0.1.5")
// REMOVE "org.koin:koin-androidx-compose:X.Y.Z" if you were using it
}
Usage
The library is using Koin's Application and Modules. The Koin documentation can be found here: https://insert-koin.io/.
The library itself contains @Composable
functions, which helps with Koin configuration:
val appModule = module {
factory { "Hello, DI!" }
}
@Preview
@Composable
fun App() {
Koin(appDeclaration = { modules(appModule) }) {
val text = get<String>()
Text(text)
}
}
Scopes are also supported:
data class A(val value: String)
val scopedModule = module {
scope<ScopeTypeA> {
scoped { A("scopeA") }
}
scope<ScopeTypeB> {
scoped { A("scopeB") }
}
}
@Preview
@Composable
fun Test() {
Koin(appDeclaration = { modules(scopedModule) }) {
Column {
KoinScope(getScope = { createScope<ScopeTypeA>() }) {
Text(get<A>().value)
}
KoinScope(getScope = { createScope<ScopeTypeB>() }) {
Text(get<A>().value)
}
}
}
}
Android ViewModel (getViewModel
, getStateViewModel
):
class MainViewModel : ViewModel() {
val data = "Hello, DI!"
}
private val viewModelModule = module {
viewModel { MainViewModel() }
}
@Composable
fun ViewModelSample() {
Koin(appDeclaration = { modules(viewModelModule) }) {
val viewModel = getViewModel<MainViewModel>()
Text(viewModel.data)
}
}
Android Compose Navigation (getNavViewModel
, getNavController
):
@Composable
fun Sample() {
val navController = rememberNavController()
Koin(appDeclaration = { modules(viewModelModule) }) {
KoinNav(navController) {
NavHost(navController, startDestination = "1") {
composable("1") {
Screen1()
}
}
}
}
}
@Composable
fun Screen1() {
val navController = getNavController()
Button(onClick = { navController.navigate("2") }) {
val navViewModel = getNavViewModel<MainViewModel>()
//...
}
}
License
Copyright 2021 Bruno Wieczorek
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.