1
1
package com.coxtunes.androidarchitecturekotlin2021.data.repository
2
+
2
3
import com.coxtunes.androidarchitecturekotlin2021.common.responseSealed.Resource
3
- import com.coxtunes.androidarchitecturekotlin2021.common.utility.DispatcherProvider
4
4
import com.coxtunes.androidarchitecturekotlin2021.data.remoteDataSource.UsersRemoteDataSource
5
5
import com.coxtunes.androidarchitecturekotlin2021.domain.repository.UserRepository
6
6
import com.coxtunes.androidarchitecturekotlin2021.domain.viewobjects.UsersViewItems
7
+ import kotlinx.coroutines.CoroutineScope
8
+ import kotlinx.coroutines.async
7
9
import kotlinx.coroutines.sync.Mutex
8
10
import kotlinx.coroutines.sync.withLock
9
- import kotlinx.coroutines.withContext
10
11
import javax.inject.Inject
11
12
12
13
/* *
13
14
* @Author: Nayeem Shiddiki Abir
14
- * @Date: 28-Dec-21
15
15
*/
16
16
class DefaultUserRepository @Inject constructor(
17
17
private val remoteDataSource : UsersRemoteDataSource ,
18
- private val dispatcher : DispatcherProvider
18
+ private val externalScope : CoroutineScope
19
19
) : UserRepository {
20
20
21
21
// Mutex to make writes to cached values thread-safe.
@@ -25,15 +25,17 @@ class DefaultUserRepository @Inject constructor(
25
25
private var latestUsersList: Resource <List <UsersViewItems >> = Resource .Empty ()
26
26
27
27
override suspend fun getUsersList (refresh : Boolean ): Resource <List <UsersViewItems >> {
28
- withContext(dispatcher.io) {
29
- val itemsRes = remoteDataSource.getUsers()
30
-
31
- // Thread-safe write to latestNews
32
- latestUsersMutex.withLock {
33
- this @DefaultUserRepository.latestUsersList = itemsRes
34
- }
28
+ return if (latestUsersList.data == null ) {
29
+ externalScope.async {
30
+ remoteDataSource.getUsers().also { userlist ->
31
+ // Thread-safe write to latestNews
32
+ latestUsersMutex.withLock {
33
+ this @DefaultUserRepository.latestUsersList = userlist
34
+ }
35
+ }
36
+ }.await()
37
+ } else {
38
+ latestUsersMutex.withLock { latestUsersList }
35
39
}
36
- return latestUsersMutex.withLock { latestUsersList }
37
40
}
38
-
39
41
}
0 commit comments