forked from joreilly/Confetti
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClientQuery.kt
More file actions
55 lines (47 loc) · 1.86 KB
/
ClientQuery.kt
File metadata and controls
55 lines (47 loc) · 1.86 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
package dev.johnoreilly.confetti.utils
import com.apollographql.apollo.ApolloCall
import com.apollographql.apollo.api.Error
import com.apollographql.apollo.api.Query
import com.apollographql.apollo.exception.ApolloException
import com.apollographql.apollo.exception.CacheMissException
import com.apollographql.cache.normalized.CacheInfo
import com.apollographql.cache.normalized.cacheInfo
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.filterNot
import kotlinx.coroutines.flow.runningFold
object ClientQuery {
fun <D : Query.Data, T> ApolloCall<D>.toUiState(
onError: (List<Error>, ApolloException?) -> Unit = { _, _ -> },
initial: QueryResult<T> = QueryResult.Loading,
mapper: (D) -> T
): Flow<QueryResult<T>> = toFlow().runningFold(initial) { previous, next ->
val apolloException = next.exception
if (next.hasErrors() || apolloException != null) {
onError(next.errors.orEmpty(), apolloException)
}
if (next.data != null) {
QueryResult.Success(mapper(next.data!!), next.cacheInfo)
} else if (apolloException is CacheMissException) {
previous
} else if (apolloException != null && previous is QueryResult.Loading) {
QueryResult.Error(apolloException)
} else {
previous
}
}.filterNot {
// Loading will be added by a QueryResult.Loading from stateIn in viewModel
// avoid here as it will cause stale results to be replaced by loading on screen
it is QueryResult.Loading
}
}
sealed interface QueryResult<out T> {
data class Error(
val exception: Exception
) : QueryResult<Nothing>
object Loading : QueryResult<Nothing>
object None : QueryResult<Nothing>
data class Success<T>(
val result: T,
val cacheInfo: CacheInfo? = null
) : QueryResult<T>
}