@@ -9,6 +9,7 @@ import kotlinx.coroutines.flow.Flow
99import kotlinx.coroutines.flow.MutableStateFlow
1010import kotlinx.coroutines.flow.StateFlow
1111import kotlinx.coroutines.flow.asStateFlow
12+ import kotlinx.coroutines.flow.combine
1213import kotlinx.coroutines.flow.distinctUntilChanged
1314import kotlinx.coroutines.flow.flow
1415import kotlinx.coroutines.flow.flowOn
@@ -17,6 +18,7 @@ import kotlinx.coroutines.flow.update
1718import kotlinx.coroutines.isActive
1819import kotlinx.coroutines.launch
1920import kotlinx.coroutines.withContext
21+ import to.bitkit.data.CacheStore
2022import to.bitkit.data.SettingsStore
2123import to.bitkit.di.BgDispatcher
2224import to.bitkit.env.Env
@@ -37,6 +39,7 @@ class CurrencyRepo @Inject constructor(
3739 @BgDispatcher private val bgDispatcher : CoroutineDispatcher ,
3840 private val currencyService : CurrencyService ,
3941 private val settingsStore : SettingsStore ,
42+ private val cacheStore : CacheStore
4043) {
4144 private val repoScope = CoroutineScope (bgDispatcher + SupervisorJob ())
4245
@@ -57,7 +60,7 @@ class CurrencyRepo @Inject constructor(
5760 init {
5861 startPolling()
5962 observeStaleData()
60- collectSettingsData ()
63+ collectCachedData ()
6164 }
6265
6366 private fun startPolling () {
@@ -82,19 +85,20 @@ class CurrencyRepo @Inject constructor(
8285 }
8386 }
8487
85- private fun collectSettingsData () {
88+ private fun collectCachedData () {
8689 repoScope.launch {
87- settingsStore.data.collect { settings ->
88- _currencyState .update { currentState ->
89- currentState.copy(
90- selectedCurrency = settings.selectedCurrency,
91- displayUnit = settings.displayUnit,
92- primaryDisplay = settings.primaryDisplay,
93- currencySymbol = currentState.rates.firstOrNull { rate ->
94- rate.quote == settings.selectedCurrency
95- }?.currencySymbol ? : " $"
96- )
97- }
90+ combine(settingsStore.data, cacheStore.data) { settings, cachedData ->
91+ _currencyState .value.copy(
92+ rates = cachedData.cachedRates,
93+ selectedCurrency = settings.selectedCurrency,
94+ displayUnit = settings.displayUnit,
95+ primaryDisplay = settings.primaryDisplay,
96+ currencySymbol = cachedData.cachedRates.firstOrNull { rate ->
97+ rate.quote == settings.selectedCurrency
98+ }?.currencySymbol ? : " $"
99+ )
100+ }.collect { newState ->
101+ _currencyState .update { newState }
98102 }
99103 }
100104 }
@@ -108,9 +112,9 @@ class CurrencyRepo @Inject constructor(
108112 isRefreshing = true
109113 try {
110114 val fetchedRates = currencyService.fetchLatestRates()
115+ cacheStore.update { it.copy(cachedRates = fetchedRates) }
111116 _currencyState .update {
112117 it.copy(
113- rates = fetchedRates,
114118 error = null ,
115119 hasStaleData = false
116120 )
0 commit comments