Skip to content

Instantly share code, notes, and snippets.

@Tetraquark
Created August 11, 2021 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tetraquark/6475fc7fcf4a911d2fc995b2bc1e841d to your computer and use it in GitHub Desktop.
Save Tetraquark/6475fc7fcf4a911d2fc995b2bc1e841d to your computer and use it in GitHub Desktop.
Kotlin Native test of Kotlin mulitplatform EventBus
import ru.tetraquark.kotlin.playground.shared.eventbus.EventBus
import kotlin.native.concurrent.TransferMode
import kotlin.native.concurrent.Worker
import kotlin.native.concurrent.freeze
class RefHolder<T>(ref: T?) {
var ref: T? = ref
get() {
val tmp = field
ref = null
return tmp
}
}
fun printEvent(tag: String, event: Any) {
println("[$tag] Got event: $event [${event::class}]")
}
fun eventBusKotlinNativeTest() {
// 1) Create observer 1 (String event) at Main thread and add it to EventBus at Main thread
val obs1 = { event: String ->
printEvent(tag = "OBS_1", event = event)
}
EventBus.observe(obs1)
// 2) Create observer 2 (String event) at Main thread and add it to EventBus at background thread
val refHolder = RefHolder(
ref = { event: String ->
printEvent(tag = "OBS_2", event = event)
}
)
val worker = Worker.start()
val addObsFuture = worker.execute(
mode = TransferMode.SAFE,
producer = { refHolder.ref },
job = {
// Adding observer 2 to EventBus at background
EventBus.observe(it!!)
}
)
addObsFuture.consume {}
// Post String event at Main thread
EventBus.post("1")
// Post String event at background thread
val fireEventFuture = worker.execute(
mode = TransferMode.SAFE,
producer = { },
job = {
// Post event to EventBus at background
EventBus.post("2")
}
)
fireEventFuture.consume {}
// Create observer 3 (Int event) at Main thread and add it to EventBus at Main thread
val obs3 = { event: Int ->
printEvent(tag = "OBS_3", event = event)
}
EventBus.observe(obs3)
// Post Int event at Main thread
EventBus.post(3)
worker.requestTermination()
}
/*
Output:
[OBS_1] Got event: 1 [class kotlin.String]
[OBS_2] Got event: 1 [class kotlin.String]
[OBS_1] Got event: 2 [class kotlin.String]
[OBS_2] Got event: 2 [class kotlin.String]
[OBS_3] Got event: 3 [class kotlin.Int]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment