Skip to content

koin: Variable injection in compose

Devrath edited this page Mar 7, 2024 · 1 revision

Composable

@Composable
fun VariableInjectionComposable(navController: NavHostController) {

    val myService = koinInject<HelloService>()

    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {

        val cxt = LocalContext.current

        AppButton(text = "Variable injection Demo", onClick = {
            Toast.makeText(cxt,myService.doSomething(),Toast.LENGTH_LONG).show()
        })


    }

}

Service Class

interface HelloService {
    fun doSomething(): String
}

Service Class Implementation

class HelloServiceImpl : HelloService {

    override fun doSomething(): String {
        return "Hello Service, Koin!"
    }

}

Define the module

val singletonService = module {
    singleOf<HelloService>(::HelloServiceImpl)
}

Application

class KotlinApplication : Application() {
    override fun onCreate() {
        super.onCreate()

        startKoin {
            androidContext(this@KotlinApplication)            
            modules(singletonService)
        }
    }
}
Clone this wiki locally