@@ -12,6 +12,7 @@ import kotlinx.coroutines.delay
1212import kotlinx.coroutines.flow.MutableSharedFlow
1313import kotlinx.coroutines.flow.asSharedFlow
1414import kotlinx.coroutines.launch
15+ import kotlinx.coroutines.withContext
1516import to.bitkit.async.ServiceQueue
1617import to.bitkit.di.BgDispatcher
1718import to.bitkit.ext.calculateRemoteBalance
@@ -44,6 +45,8 @@ class GiftViewModel @Inject constructor(
4445 private var code: String = " "
4546 var amount: ULong = 0uL
4647 private set
48+
49+ @Volatile
4750 private var isClaiming: Boolean = false
4851
4952 fun initialize (code : String , amount : ULong ) {
@@ -54,16 +57,17 @@ class GiftViewModel @Inject constructor(
5457 }
5558 this .code = code
5659 this .amount = amount
57- claimGift()
58- }
59-
60- private fun claimGift () = viewModelScope.launch(bgDispatcher) {
61- if (isClaiming) {
62- return @launch
60+ viewModelScope.launch(bgDispatcher) {
61+ claimGift()
6362 }
63+ }
6464
65+ @Suppress(" TooGenericExceptionCaught" )
66+ private suspend fun claimGift () = withContext(bgDispatcher) {
67+ if (isClaiming) return @withContext
6568 isClaiming = true
66- runCatching {
69+
70+ try {
6771 lightningRepo.executeWhenNodeRunning(
6872 operationName = " waitForNodeRunning" ,
6973 waitTimeout = NODE_STARTUP_TIMEOUT_MS .milliseconds,
@@ -81,9 +85,10 @@ class GiftViewModel @Inject constructor(
8185 } else {
8286 claimWithoutLiquidity()
8387 }
84- }.onFailure { e ->
85- isClaiming = false
88+ } catch (e: Exception ) {
8689 handleGiftClaimError(e)
90+ } finally {
91+ isClaiming = false
8792 }
8893 }
8994
@@ -99,10 +104,8 @@ class GiftViewModel @Inject constructor(
99104 giftPay(invoice = invoice)
100105 }
101106
102- isClaiming = false
103107 _navigationEvent .emit(GiftRoute .Success )
104108 }.onFailure { e ->
105- isClaiming = false
106109 handleGiftClaimError(e)
107110 }
108111 }
@@ -139,7 +142,6 @@ class GiftViewModel @Inject constructor(
139142
140143 activityRepo.insertActivity(Activity .Lightning (lightningActivity)).getOrThrow()
141144
142- isClaiming = false
143145 _successEvent .emit(
144146 NewTransactionSheetDetails (
145147 type = NewTransactionSheetType .LIGHTNING ,
@@ -150,7 +152,6 @@ class GiftViewModel @Inject constructor(
150152 )
151153 _navigationEvent .emit(GiftRoute .Success )
152154 }.onFailure { e ->
153- isClaiming = false
154155 handleGiftClaimError(e)
155156 }
156157 }
0 commit comments