|
1 | 1 | package com.threegap.bitnagil.data.user.repositoryImpl |
2 | 2 |
|
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 |
4 | 5 | import com.threegap.bitnagil.data.user.model.response.toDomain |
5 | 6 | import com.threegap.bitnagil.domain.user.model.UserProfile |
6 | 7 | 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 |
7 | 15 | import javax.inject.Inject |
| 16 | +import javax.inject.Singleton |
8 | 17 |
|
| 18 | +@Singleton |
9 | 19 | class UserRepositoryImpl @Inject constructor( |
10 | | - private val userDataSource: UserDataSource, |
| 20 | + private val userLocalDataSource: UserLocalDataSource, |
| 21 | + private val userRemoteDataSource: UserRemoteDataSource, |
11 | 22 | ) : 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 | + } |
14 | 50 | } |
0 commit comments