Skip to content

koin: Injecting the interface in constructor of viewModel

Devrath edited this page Mar 7, 2024 · 1 revision

Interface as Service

interface HelloService {
    fun doSomething(): String
}

Implementation of Service

class HelloServiceImpl : HelloService {

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

}

Kotlin Module

val viewModelModules = module {
    viewModel { VariableInjectionVm(get()) }
}

ViewModel

class VariableInjectionVm(
    private val helloService: HelloService
) : ViewModel() {
    fun demo(): String {
        return helloService.doSomething()
    }
}
Clone this wiki locally