-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathBaseHybridViewModelPropertyImpl.kt
More file actions
69 lines (61 loc) · 1.62 KB
/
BaseHybridViewModelPropertyImpl.kt
File metadata and controls
69 lines (61 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.margelo.nitro.rive
import androidx.annotation.Keep
import com.facebook.proguard.annotations.DoNotStrip
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.drop
import java.lang.ref.WeakReference
import java.util.UUID
@Keep
@DoNotStrip
class BaseHybridViewModelPropertyImpl<T> : BaseHybridViewModelProperty<T> {
override var scope: CoroutineScope? = null
override var job: Job? = null
override val listeners = mutableMapOf<String, (T) -> Unit>()
override fun ensureValueListenerJob(valueFlow: Flow<T>, drop: Int) {
if (scope == null) {
scope = CoroutineScope(Dispatchers.Default)
}
if (job == null) {
job = scope?.launch {
valueFlow.drop(drop).collect { value ->
onChanged(value)
}
}
}
}
override fun onChanged(value: T) {
listeners.values.forEach { listener ->
listener(value)
}
}
override fun addListenerInternal(callback: (T) -> Unit): () -> Unit {
val id = UUID.randomUUID().toString()
listeners[id] = callback
val weakSelf = WeakReference(this)
return {
weakSelf.get()?.removeListener(id)
}
}
override fun removeListener(id: String) {
listeners.remove(id)
if (listeners.isEmpty()) {
job?.cancel()
job = null
}
}
override fun removeListeners() {
listeners.clear()
job?.cancel()
scope?.cancel()
job = null
scope = null
}
override fun dispose() {
removeListeners()
}
}