Created
March 31, 2018 03:57
-
-
Save aoriani/063df11c637fb781cc55202c4fd40fba to your computer and use it in GitHub Desktop.
A simple implementation of Event Bus using Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.aoriani.simplebutterknife | |
import android.support.v7.app.AppCompatActivity | |
import android.os.Bundle | |
import android.view.View | |
import android.widget.TextView | |
import kotlin.reflect.KClass | |
import kotlin.reflect.KFunction | |
import kotlin.reflect.full.declaredMemberFunctions | |
import kotlin.reflect.jvm.jvmErasure | |
class BusActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
EvenBus.register(this) | |
setContentView(R.layout.activity_bus) | |
findViewById<View>(R.id.button).setOnClickListener { | |
EvenBus.post("Hi Earth!") | |
} | |
} | |
@Suppress("unused") | |
@Subscribe | |
fun onEvent(event: String) { | |
findViewById<TextView>(R.id.textView).text = event | |
} | |
} | |
@Target(AnnotationTarget.FUNCTION) | |
@Retention(AnnotationRetention.RUNTIME) | |
annotation class Subscribe | |
object EvenBus { | |
private val register = HashMap<KClass<*>, MutableList<Pair<Any, KFunction<*>>>>() | |
fun register(subscriber: Any) { | |
subscriber::class.declaredMemberFunctions | |
.filter { it.annotations.any { it is Subscribe } && it.parameters.size == 2 && it.returnType.jvmErasure == Unit::class } | |
.forEach { | |
val eventType = it.parameters[1].type.jvmErasure | |
if (eventType !in register) { | |
register[eventType] = arrayListOf() | |
} | |
register[eventType]?.add(subscriber to it) | |
} | |
} | |
fun post(event: Any) { | |
register[event::class]?.forEach { | |
it.second.call(it.first, event) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment