Update Event.kt

This commit is contained in:
CranberrySoup 2024-01-18 14:49:56 +00:00 committed by GitHub
parent 5dfc08aabb
commit dce83437f1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,9 +1,13 @@
package com.lagradost.cloudstream3.utils package com.lagradost.cloudstream3.utils
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
class Event<T> { class Event<T> {
private val observers = mutableSetOf<(T) -> Unit>() private val observers = mutableSetOf<(T) -> Unit>()
val size : Int get() = observers.size val size: Int get() = observers.size
operator fun plusAssign(observer: (T) -> Unit) { operator fun plusAssign(observer: (T) -> Unit) {
observers.add(observer) observers.add(observer)
@ -13,8 +17,14 @@ class Event<T> {
observers.remove(observer) observers.remove(observer)
} }
private val invokeMutex = Mutex()
operator fun invoke(value: T) { operator fun invoke(value: T) {
ioSafe {
invokeMutex.withLock { // Can crash otherwise
for (observer in observers) for (observer in observers)
observer(value) observer(value)
} }
}
}
} }