@@ -7,9 +7,12 @@ import com.cornellappdev.android.eatery.data.models.Event
77import com.cornellappdev.android.eatery.ui.viewmodels.state.EateryApiResponse
88import kotlinx.coroutines.CoroutineScope
99import kotlinx.coroutines.Dispatchers
10+ import kotlinx.coroutines.flow.Flow
1011import kotlinx.coroutines.flow.MutableStateFlow
1112import kotlinx.coroutines.flow.StateFlow
1213import kotlinx.coroutines.flow.asStateFlow
14+ import kotlinx.coroutines.flow.map
15+ import kotlinx.coroutines.flow.update
1316import kotlinx.coroutines.launch
1417import javax.inject.Inject
1518import javax.inject.Singleton
@@ -95,8 +98,8 @@ class EateryRepository @Inject constructor(private val networkApi: NetworkApi) {
9598 /* *
9699 * A map from eatery ids to the states representing their API loading calls.
97100 */
98- private val eateryApiCache: MutableMap <Int , MutableStateFlow < EateryApiResponse <Eatery >>> =
99- mutableMapOf ()
101+ private val eateryApiCache: MutableStateFlow < MutableMap <Int , EateryApiResponse <Eatery >>> =
102+ MutableStateFlow ( mutableMapOf () )
100103
101104 /* *
102105 * Makes a new call to backend for the specified eatery. After calling,
@@ -105,31 +108,33 @@ class EateryRepository @Inject constructor(private val networkApi: NetworkApi) {
105108 */
106109 private fun pingEatery (eateryId : Int ) {
107110 // If first time calling, make new state.
108- if (eateryApiCache[eateryId] == null ) {
109- eateryApiCache[eateryId] = MutableStateFlow (EateryApiResponse .Pending )
110- }
111-
112- eateryApiCache[eateryId]!! .value = EateryApiResponse .Pending
111+ updateCache(eateryId, EateryApiResponse .Pending )
113112
114113 CoroutineScope (Dispatchers .IO ).launch {
115114 try {
116115 val eatery = getEatery(eateryId = eateryId)
117- eateryApiCache[ eateryId] !! .value = EateryApiResponse .Success (eatery)
116+ updateCache( eateryId, EateryApiResponse .Success (eatery) )
118117 } catch (_: Exception ) {
119- eateryApiCache[ eateryId] !! .value = EateryApiResponse .Error
118+ updateCache( eateryId, EateryApiResponse .Error )
120119 }
121120 }
122121 }
123122
123+ private fun updateCache (eateryId : Int , response : EateryApiResponse <Eatery >) {
124+ eateryApiCache.update {
125+ (it + (eateryId to response)).toMutableMap()
126+ }
127+ }
128+
124129 /* *
125130 * Returns the [StateFlow] representing the API call for the specified eatery.
126131 * If ALL eateries are already loaded, then this simply instantly returns that.
127132 */
128- fun getEateryFlow (eateryId : Int ): StateFlow <EateryApiResponse <Eatery >> {
133+ fun getEateryFlow (eateryId : Int ): Flow <EateryApiResponse <Eatery >> {
129134 lastEateryId = eateryId
130- if (! eateryApiCache.contains(eateryId)) {
135+ if (! eateryApiCache.value. contains(eateryId)) {
131136 pingEatery(eateryId)
132137 }
133- return eateryApiCache[eateryId]!!
138+ return eateryApiCache.map { it [eateryId]!! }
134139 }
135140}
0 commit comments