@@ -33,8 +33,10 @@ import com.flipcash.libs.coroutines.DispatcherProvider
3333import com.getcode.view.BaseViewModel2
3434import com.getcode.view.LoadingSuccessState
3535import dagger.hilt.android.lifecycle.HiltViewModel
36+ import kotlinx.coroutines.CompletableDeferred
3637import kotlinx.coroutines.flow.combine
3738import kotlinx.coroutines.flow.distinctUntilChanged
39+ import kotlinx.coroutines.flow.drop
3840import kotlinx.coroutines.flow.filter
3941import kotlinx.coroutines.flow.filterIsInstance
4042import kotlinx.coroutines.flow.filterNotNull
@@ -64,6 +66,7 @@ internal class CashScreenViewModel @Inject constructor(
6466) {
6567
6668 private val numberInputHelper = NumberInputHelper ()
69+ private val tokenInitialized = CompletableDeferred <Mint ?>()
6770
6871 internal data class State (
6972 val selectedTokenAddress : Mint ? = null ,
@@ -101,6 +104,7 @@ internal class CashScreenViewModel @Inject constructor(
101104 }
102105
103106 sealed interface Event {
107+ data class InitializeToken (val mint : Mint ? ) : Event
104108 data class OnTokenSelected (val address : Mint ) : Event
105109 data class OnTokenUpdated (val token : TokenWithLocalizedBalance ) : Event
106110 data class OnNumberPressed (val number : Int ) : Event
@@ -187,10 +191,24 @@ internal class CashScreenViewModel @Inject constructor(
187191 init {
188192 numberInputHelper.reset()
189193
190- tokenCoordinator.observeSelectedTokenMint()
191- .distinctUntilChanged()
192- .onEach { dispatchEvent(Event .OnTokenSelected (it)) }
193- .launchIn(viewModelScope)
194+ eventFlow
195+ .filterIsInstance<Event .InitializeToken >()
196+ .take(1 )
197+ .onEach { event ->
198+ if (event.mint != null ) {
199+ dispatchEvent(Event .OnTokenSelected (event.mint))
200+ }
201+ tokenInitialized.complete(event.mint)
202+ }.launchIn(viewModelScope)
203+
204+ viewModelScope.launch {
205+ val navMint = tokenInitialized.await()
206+ tokenCoordinator.observeSelectedTokenMint()
207+ .distinctUntilChanged()
208+ .let { if (navMint != null ) it.drop(1 ) else it }
209+ .onEach { dispatchEvent(Event .OnTokenSelected (it)) }
210+ .launchIn(viewModelScope)
211+ }
194212
195213 stateFlow
196214 .mapNotNull { it.selectedTokenAddress }
@@ -375,6 +393,8 @@ internal class CashScreenViewModel @Inject constructor(
375393 state.copy(preferredOnRampProvider = event.provider)
376394 }
377395
396+ is Event .InitializeToken -> { state -> state }
397+
378398 is Event .OpenOnRampAmountModal -> { state -> state }
379399
380400 is Event .OpenScreen -> { state -> state }
0 commit comments