Skip to content

Instantly share code, notes, and snippets.

@LucasAlfare
Last active November 25, 2022 15:45
Show Gist options
  • Save LucasAlfare/f5405f0f67e8a66eda8f69c29d30d51f to your computer and use it in GitHub Desktop.
Save LucasAlfare/f5405f0f67e8a66eda8f69c29d30d51f to your computer and use it in GitHub Desktop.
rasc multiple coroutines
import kotlinx.coroutines.*
abstract class Manageable {
private val listeners = mutableListOf<Manageable>()
var initiated = false
abstract suspend fun init()
abstract fun onEvent(e: String, data: Any? = null)
fun addListener(l: Manageable) {
if (!listeners.contains(l)) {
listeners += l
}
}
fun notifyListeners(e: String, data: Any? = null) {
listeners.forEach { it.onEvent(e, data) }
}
}
class Manager1 : Manageable() {
override suspend fun init() {
println("${this.javaClass.name} is initiating...")
val startTime = System.currentTimeMillis()
while (!initiated) {
if (System.currentTimeMillis() - startTime >= 8_000L) {
initiated = true
}
}
val n = 254354
println("${this.javaClass.name} finished initialization. Sending the result value of n=$n to the listeners...")
notifyListeners("resultado_aleatorio", n)
}
override fun onEvent(e: String, data: Any?) {
if (e == "sou o 2 terminei") {
println("${this.javaClass.name} received the event=$e. The data is data=$data")
}
}
}
class Manager2 : Manageable() {
override suspend fun init() {
println("${this.javaClass.name} is initiating...")
val startTime = System.currentTimeMillis()
while (!initiated) {
if (System.currentTimeMillis() - startTime >= 1_000L) {
initiated = true
}
}
notifyListeners("sou o 2 terminei", "hahahahahaha!")
println("${this.javaClass.name} finished initialization.")
}
override fun onEvent(e: String, data: Any?) {
if (e == "resultado_aleatorio") {
println("${this.javaClass.name} received the event=$e. The data is data=$data")
}
}
}
suspend fun setupManagers(vararg managers: Manageable) {
managers.forEach { m1 ->
managers.forEach { m2 ->
if (m2 != m1) {
m1.addListener(m2)
}
}
}
coroutineScope {
managers.forEach {
launch { it.init() }
}
launch {
while (true) {
val nFinished = managers.count { it.initiated }
if (nFinished == managers.size) {
println("TUDO INICIADO!!!!")
break
}
}
}
}
}
suspend fun main() {
setupManagers(
Manager1(),
Manager2()
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment