https://start.insert-koin.io/#/quickstart/kotlin?id=getting-started-with-kotlin-app

开始

Koin in 5 minutes (5分钟快速入手Koin)

Getting Started (开始)

在Kotlin app中使用

本教程将会告诉你如何使用Koin注入和检索组件来编写一个Kotlin app。

获取实例代码

可以直接在Github上查看项目或者下载zip

🚀 Go to Github or download Zip

配置

首先,检查下 koin-core 依赖是不是按照如下形式添加了:

1
2
3
4
5
6
7
8
9
10
// Add Jcenter to your repositories if needed
repositories {
jcenter()
}
dependencies {
// Koin for Kotlin apps
compile "org.koin:koin-core:$koin_version"
// Testing
testCompile "org.koin:koin-test:$koin_version"
}

Application

在我们的小型App上,我们只需要有2个组件:

  • HelloMessageData - 持有数据(data)
  • HelloService - 使用和显示HelloMessageData上的数据
  • HelloApplication - 检索和使用HelloService

Data holder

让我们创建一个 HelloMessageData 数据类来持有我们的数据:

1
2
3
4
/**
* A class to hold our message data
*/
data class HelloMessageData(val message : String = "Hello Koin!")

Service

让我们创建一个service来显示 HelloMessageData 中的数据。写一个 HelloServiceImpl 类以及他的接口 HelloService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Hello Service - interface
*/
interface HelloService {
fun hello(): String
}


/**
* Hello Service Impl
* Will use HelloMessageData data
*/
class HelloServiceImpl(private val helloMessageData: HelloMessageData) : HelloService {

override fun hello() = "Hey, ${helloMessageData.message}"
}

The application class

为了让HelloService组件能运行,我们还需要创建一个runtime组件。

让我们写一个 HelloApplication 类并让他实现 KoinComponent 接口。这能让我们稍后可以通过 by inject() 函数来检索我们的组件:

1
2
3
4
5
6
7
8
9
10
11
12
/**
* HelloApplication - Application Class
* use HelloService
*/
class HelloApplication : KoinComponent {

// Inject HelloService
val helloService by inject<HelloService>()

// display our data
fun sayHello() = println(helloService.hello())
}

声明依赖

现在,让我们使用Koin module来将 HelloMessageDataHelloService 组装在一起:

1
2
3
4
5
6
val helloModule = module {

single { HelloMessageData() }

single { HelloServiceImpl(get()) as HelloService }
}

我们使用 single 来将每一个组件声明成单例对象。

  • single { HelloMessageData() } : 声明一个单例的 HelloMessageData 对象
  • single { HelloServiceImpl(get()) as HelloService } : 使用注入的 HelloMessageData 来构造HelloServiceImpl 对象,并声明成 HelloService 的单例对象。

这就完成啦!

只需要通过一个 main 函数来启动我们的app:

1
2
3
4
5
6
7
8
9
10
11
fun main(vararg args: String) {

startKoin {
// use Koin logger
printLogger()
// declare modules
modules(helloModule)
}

HelloApplication().sayHello()
}