11package io.snabble.sdk
22
3+ import android.os.Looper
34import android.os.Parcelable
45import androidx.annotation.Keep
56import androidx.lifecycle.LiveData
@@ -69,9 +70,8 @@ enum class CouponSource {
6970}
7071
7172class Coupons (
72- coupons : List <Coupon >,
7373 private val project : Project
74- ) : Iterable<Coupon>, LiveData<List<Coupon>>(coupons ) {
74+ ) : Iterable<Coupon>, LiveData<List<Coupon>>() {
7575 val source: LiveData <CouponSource > = MutableLiveData (CouponSource .Bundled )
7676 val isLoading: LiveData <Boolean > = MutableLiveData (false )
7777
@@ -97,16 +97,19 @@ class Coupons (
9797
9898 fun update () {
9999 if (isLoading.value == true ) return
100- // make an implicit cast with an extension function
101- fun <T > LiveData<T>.postValue (value : T ) {
102- (this as ? MutableLiveData <T >)?.postValue(value)
100+ fun <T > LiveData<T>.setAsap (value : T ) {
101+ if (Looper .getMainLooper().thread.id == Thread .currentThread().id) {
102+ (this as MutableLiveData <T >).value = value
103+ } else {
104+ (this as MutableLiveData <T >).postValue(value)
105+ }
103106 }
104107 project.urls[" coupons" ]?.let { path ->
105- isLoading.postValue (true )
108+ isLoading.setAsap (true )
106109 val newsUrl = Snabble .getInstance().absoluteUrl(path)
107110
108111 if (newsUrl == null ) {
109- postValue (emptyList())
112+ setProjectCoupons (emptyList())
110113 return
111114 }
112115
@@ -117,8 +120,8 @@ class Coupons (
117120 couponCall.enqueue(object : Callback {
118121 override fun onFailure (call : Call , e : IOException ) {
119122 postValue(emptyList())
120- isLoading.postValue (false )
121- source.postValue (CouponSource .Online )
123+ isLoading.setAsap (false )
124+ source.setAsap (CouponSource .Online )
122125 }
123126
124127 override fun onResponse (call : Call , response : Response ) {
@@ -128,14 +131,23 @@ class Coupons (
128131 postValue(localizedResponse.coupons.filter { coupon ->
129132 coupon.isValid
130133 })
131- source.postValue (CouponSource .Online )
134+ source.setAsap (CouponSource .Online )
132135 }
133- isLoading.postValue (false )
136+ isLoading.setAsap (false )
134137 }
135138 })
136139 }
137140 }
138141
142+ // Visibility for Project class. Used for setting the data asap if on main thread
143+ internal fun setProjectCoupons (coupons : List <Coupon >) {
144+ if (Looper .getMainLooper().thread.id == Thread .currentThread().id) {
145+ value = coupons
146+ } else {
147+ postValue(coupons)
148+ }
149+ }
150+
139151 @Keep
140152 private data class CouponResponse (
141153 val coupons : List <Coupon >
0 commit comments