1 /*
2  * Copyright 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package androidx.paging
18 
19 import androidx.annotation.RestrictTo
20 import androidx.paging.LoadState.NotLoading
21 import kotlin.jvm.JvmName
22 
23 /** Collection of pagination [LoadState]s - refresh, prepend, and append. */
24 @Suppress("DataClassDefinition")
25 public data class LoadStates(
26     /** [LoadState] corresponding to [LoadType.REFRESH] loads. */
27     public val refresh: LoadState,
28     /** [LoadState] corresponding to [LoadType.PREPEND] loads. */
29     public val prepend: LoadState,
30     /** [LoadState] corresponding to [LoadType.APPEND] loads. */
31     public val append: LoadState
32 ) {
33     @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
forEachnull34     public inline fun forEach(op: (LoadType, LoadState) -> Unit) {
35         op(LoadType.REFRESH, refresh)
36         op(LoadType.PREPEND, prepend)
37         op(LoadType.APPEND, append)
38     }
39 
modifyStatenull40     internal fun modifyState(loadType: LoadType, newState: LoadState): LoadStates {
41         return when (loadType) {
42             LoadType.APPEND -> copy(append = newState)
43             LoadType.PREPEND -> copy(prepend = newState)
44             LoadType.REFRESH -> copy(refresh = newState)
45         }
46     }
47 
getnull48     internal fun get(loadType: LoadType) =
49         when (loadType) {
50             LoadType.REFRESH -> refresh
51             LoadType.APPEND -> append
52             LoadType.PREPEND -> prepend
53         }
54 
55     /** Returns true if either one of [refresh], [append], or [prepend] is in [Error] state. */
56     @get:JvmName("hasError")
57     public val hasError =
58         refresh is LoadState.Error || append is LoadState.Error || prepend is LoadState.Error
59 
60     /**
61      * Returns true if all three LoadState [refresh], [append], and [prepend] are in [NotLoading]
62      * state.
63      */
64     public val isIdle = refresh is NotLoading && append is NotLoading && prepend is NotLoading
65 
66     internal companion object {
67         val IDLE =
68             LoadStates(
69                 refresh = NotLoading.Incomplete,
70                 prepend = NotLoading.Incomplete,
71                 append = NotLoading.Incomplete
72             )
73     }
74 }
75