Skip to content

Commit 9236266

Browse files
committed
Feat: UserRepository 내 캐싱 로직 및 Mutex를 이용한 Race Condition 방지 로직 구현
1 parent 46ea194 commit 9236266

2 files changed

Lines changed: 43 additions & 5 deletions

File tree

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,50 @@
11
package com.threegap.bitnagil.data.user.repositoryImpl
22

3-
import com.threegap.bitnagil.data.user.datasource.UserDataSource
3+
import com.threegap.bitnagil.data.user.datasource.UserLocalDataSource
4+
import com.threegap.bitnagil.data.user.datasource.UserRemoteDataSource
45
import com.threegap.bitnagil.data.user.model.response.toDomain
56
import com.threegap.bitnagil.domain.user.model.UserProfile
67
import com.threegap.bitnagil.domain.user.repository.UserRepository
8+
import kotlinx.coroutines.flow.Flow
9+
import kotlinx.coroutines.flow.emitAll
10+
import kotlinx.coroutines.flow.filterNotNull
11+
import kotlinx.coroutines.flow.flow
12+
import kotlinx.coroutines.flow.map
13+
import kotlinx.coroutines.sync.Mutex
14+
import kotlinx.coroutines.sync.withLock
715
import javax.inject.Inject
16+
import javax.inject.Singleton
817

18+
@Singleton
919
class UserRepositoryImpl @Inject constructor(
10-
private val userDataSource: UserDataSource,
20+
private val userLocalDataSource: UserLocalDataSource,
21+
private val userRemoteDataSource: UserRemoteDataSource,
1122
) : UserRepository {
12-
override suspend fun fetchUserProfile(): Result<UserProfile> =
13-
userDataSource.fetchUserProfile().map { it.toDomain() }
23+
private val fetchMutex = Mutex()
24+
25+
override fun observeUserProfile(): Flow<Result<UserProfile>> = flow {
26+
if (userLocalDataSource.userProfile.value == null) {
27+
fetchMutex.withLock {
28+
if (userLocalDataSource.userProfile.value == null) {
29+
userRemoteDataSource.fetchUserProfile()
30+
.onSuccess { response ->
31+
userLocalDataSource.saveUserProfile(response.toDomain())
32+
}
33+
.onFailure {
34+
emit(Result.failure(it))
35+
}
36+
}
37+
}
38+
}
39+
40+
emitAll(
41+
userLocalDataSource.userProfile
42+
.filterNotNull()
43+
.map { Result.success(it) },
44+
)
45+
}
46+
47+
override fun clearCache() {
48+
userLocalDataSource.clearCache()
49+
}
1450
}
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package com.threegap.bitnagil.domain.user.repository
22

33
import com.threegap.bitnagil.domain.user.model.UserProfile
4+
import kotlinx.coroutines.flow.Flow
45

56
interface UserRepository {
6-
suspend fun fetchUserProfile(): Result<UserProfile>
7+
fun observeUserProfile(): Flow<Result<UserProfile>>
8+
fun clearCache()
79
}

0 commit comments

Comments
 (0)