-
Notifications
You must be signed in to change notification settings - Fork 614
Expand file tree
/
Copy pathDataRepository.kt
More file actions
66 lines (57 loc) · 2.05 KB
/
Copy pathDataRepository.kt
File metadata and controls
66 lines (57 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.task.data
import com.task.data.dto.login.LoginRequest
import com.task.data.dto.login.LoginResponse
import com.task.data.dto.recipes.Recipes
import com.task.data.local.LocalData
import com.task.data.remote.RemoteData
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import javax.inject.Inject
import kotlin.coroutines.CoroutineContext
/**
* Created by AhmedEltaher
*/
class DataRepository @Inject constructor(
private val remoteRepository: RemoteData,
private val localRepository: LocalData,
private val ioDispatcher: CoroutineContext
) : DataRepositorySource {
override suspend fun requestRecipes(): Flow<Resource<Recipes>> {
return flow {
emit(remoteRepository.requestRecipes())
}.flowOn(ioDispatcher)
}
override suspend fun doLogin(loginRequest: LoginRequest): Flow<Resource<LoginResponse>> {
return flow {
emit(localRepository.doLogin(loginRequest))
}.flowOn(ioDispatcher)
}
override suspend fun addToFavourite(id: String): Flow<Resource<Boolean>> {
return flow {
localRepository.getCachedFavourites().let {
it.data?.toMutableSet()?.let { set ->
val isAdded = set.add(id)
if (isAdded) {
emit(localRepository.cacheFavourites(set))
} else {
emit(Resource.Success(false))
}
}
it.errorCode?.let { errorCode ->
emit(Resource.DataError<Boolean>(errorCode))
}
}
}.flowOn(ioDispatcher)
}
override suspend fun removeFromFavourite(id: String): Flow<Resource<Boolean>> {
return flow {
emit(localRepository.removeFromFavourites(id))
}.flowOn(ioDispatcher)
}
override suspend fun isFavourite(id: String): Flow<Resource<Boolean>> {
return flow {
emit(localRepository.isFavourite(id))
}.flowOn(ioDispatcher)
}
}