Kotlin:我们可以在 Kotlin 中使用 EventBus(GreenRobot)的@Subscribe 吗?
Kotlin: Can we use @Subscribe of EventBus (GreenRobot) in Kotlin?
我的 onEvent 片段如下,在我的 Kotlin 函数中捕获 activity 的身份验证。但是,我无法触发 onEvent。
@Subscribe
fun onEvent(event: AuthenticationEvent) {
if (event.isAuthenticated) {
startFragment(signInFragment, SignInFragment.TAG)
} else {
startFragment(signOutFragment, SignOutFragment.TAG)
}
}
在我的 build.gradle 文件中,我添加了这个
compile 'org.greenrobot:eventbus:3.0.0'
我需要做些什么来获得这个触发器吗?
您可以使用 Square 的 Otto,它的工作方式相同,并且与 Kotlin 完美配合。虽然,要小心,因为 EventBuses 容易使代码过于复杂 Android,这就是为什么他们不赞成使用 Rx 框架。
要在 Kotlin 中使用注释处理器,您需要使用 Kotlin Annotation Processor tool (kapt)。
将此添加到您的 build.gradle
:
apply plugin: 'kotlin-kapt'
According to GreenRobot(并通过我的测试证实),这就是你需要得到 @Subscribe
.
- 确保带有
@Subscribe
注释的事件处理函数是 public
在build.gradle
文件中添加代码:
apply plugin: 'kotlin-kapt'
implementation "org.greenrobot:eventbus:3.0.0"
kapt 'org.greenrobot:eventbus-annotation-processor:3.0.1'
如果你想使用Subscriber Index
,你也将代码添加到build.gradle
:
kapt {
arguments {
arg('eventBusIndex', 'your-package.MyEventBusIndex')
}
}
我的 onEvent 片段如下,在我的 Kotlin 函数中捕获 activity 的身份验证。但是,我无法触发 onEvent。
@Subscribe
fun onEvent(event: AuthenticationEvent) {
if (event.isAuthenticated) {
startFragment(signInFragment, SignInFragment.TAG)
} else {
startFragment(signOutFragment, SignOutFragment.TAG)
}
}
在我的 build.gradle 文件中,我添加了这个
compile 'org.greenrobot:eventbus:3.0.0'
我需要做些什么来获得这个触发器吗?
您可以使用 Square 的 Otto,它的工作方式相同,并且与 Kotlin 完美配合。虽然,要小心,因为 EventBuses 容易使代码过于复杂 Android,这就是为什么他们不赞成使用 Rx 框架。
要在 Kotlin 中使用注释处理器,您需要使用 Kotlin Annotation Processor tool (kapt)。
将此添加到您的 build.gradle
:
apply plugin: 'kotlin-kapt'
According to GreenRobot(并通过我的测试证实),这就是你需要得到 @Subscribe
.
- 确保带有
@Subscribe
注释的事件处理函数是 public 在
build.gradle
文件中添加代码:apply plugin: 'kotlin-kapt' implementation "org.greenrobot:eventbus:3.0.0" kapt 'org.greenrobot:eventbus-annotation-processor:3.0.1'
如果你想使用
Subscriber Index
,你也将代码添加到build.gradle
:kapt { arguments { arg('eventBusIndex', 'your-package.MyEventBusIndex') } }