@@ -6,6 +6,7 @@ import androidx.core.os.LocaleListCompat
66import okhttp3.*
77import okhttp3.RequestBody.Companion.toRequestBody
88import org.json.JSONObject
9+ import java.lang.ref.WeakReference
910import java.util.*
1011import kotlin.properties.Delegates
1112
@@ -18,9 +19,11 @@ class Pluto private constructor() {
1819
1920 internal val data by lazy { PlutoModel (context!! ) }
2021
21- private var stateObserver : (( State ) -> Unit ) ? = null
22+ private val stateObserverList = mutableListOf< WeakReference <( State ) - > Unit >> ()
2223 internal var state: State by Delegates .observable(State .loading) { _, _, new ->
23- stateObserver?.let { it(new) }
24+ for (observer in stateObserverList) {
25+ observer.get()?.let { it(new) }
26+ }
2427 }
2528
2629 private val client by lazy { OkHttpClient () }
@@ -73,8 +76,19 @@ class Pluto private constructor() {
7376 client.newCall(request).enqueue(callback)
7477 }
7578
76- fun observeState (observer : ((State ) -> Unit )? ) {
77- stateObserver = observer
79+ fun addStateObserver (observer : ((State ) -> Unit )) {
80+ stateObserverList.add(WeakReference (observer))
81+ }
82+
83+ fun removeStateObserver (observer : ((State ) -> Unit )) {
84+ stateObserverList.removeAll {
85+ val o = it.get()
86+ o == null || o == observer
87+ }
88+ }
89+
90+ fun removeAllStateObserver () {
91+ stateObserverList.clear()
7892 }
7993
8094 fun currentState () = state
@@ -83,6 +97,7 @@ class Pluto private constructor() {
8397 client.dispatcher.executorService.shutdown()
8498 client.connectionPool.evictAll()
8599 client.cache?.close()
100+ removeAllStateObserver()
86101 }
87102
88103 init {
0 commit comments