Last active
November 25, 2022 15:45
-
-
Save LucasAlfare/f5405f0f67e8a66eda8f69c29d30d51f to your computer and use it in GitHub Desktop.
rasc multiple coroutines
This file contains hidden or 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
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