1 /*
<lambda>null2  * 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.paging.LoadState.NotLoading
20 import kotlin.jvm.JvmName
21 import kotlin.jvm.JvmSuppressWildcards
22 import kotlinx.coroutines.FlowPreview
23 import kotlinx.coroutines.flow.Flow
24 import kotlinx.coroutines.flow.debounce
25 import kotlinx.coroutines.flow.filter
26 import kotlinx.coroutines.flow.firstOrNull
27 
28 /**
29  * Collection of pagination [LoadState]s for both a [PagingSource], and [RemoteMediator].
30  *
31  * Note: The [LoadType] [REFRESH][LoadType.REFRESH] always has [LoadState.endOfPaginationReached]
32  * set to `false`.
33  */
34 public class CombinedLoadStates(
35     /**
36      * Convenience for combined behavior of [REFRESH][LoadType.REFRESH] [LoadState], which generally
37      * defers to [mediator] if it exists, but if previously was [LoadState.Loading], awaits for both
38      * [source] and [mediator] to become [LoadState.NotLoading] to ensure the remote load was
39      * applied.
40      *
41      * For use cases that require reacting to [LoadState] of [source] and [mediator] specifically,
42      * e.g., showing cached data when network loads via [mediator] fail, [LoadStates] exposed via
43      * [source] and [mediator] should be used directly.
44      */
45     public val refresh: LoadState,
46     /**
47      * Convenience for combined behavior of [PREPEND][LoadType.REFRESH] [LoadState], which generally
48      * defers to [mediator] if it exists, but if previously was [LoadState.Loading], awaits for both
49      * [source] and [mediator] to become [LoadState.NotLoading] to ensure the remote load was
50      * applied.
51      *
52      * For use cases that require reacting to [LoadState] of [source] and [mediator] specifically,
53      * e.g., showing cached data when network loads via [mediator] fail, [LoadStates] exposed via
54      * [source] and [mediator] should be used directly.
55      */
56     public val prepend: LoadState,
57     /**
58      * Convenience for combined behavior of [APPEND][LoadType.REFRESH] [LoadState], which generally
59      * defers to [mediator] if it exists, but if previously was [LoadState.Loading], awaits for both
60      * [source] and [mediator] to become [LoadState.NotLoading] to ensure the remote load was
61      * applied.
62      *
63      * For use cases that require reacting to [LoadState] of [source] and [mediator] specifically,
64      * e.g., showing cached data when network loads via [mediator] fail, [LoadStates] exposed via
65      * [source] and [mediator] should be used directly.
66      */
67     public val append: LoadState,
68     /** [LoadStates] corresponding to loads from a [PagingSource]. */
69     public val source: LoadStates,
70 
71     /**
72      * [LoadStates] corresponding to loads from a [RemoteMediator], or `null` if [RemoteMediator]
73      * not present.
74      */
75     public val mediator: LoadStates? = null,
76 ) {
77 
78     override fun equals(other: Any?): Boolean {
79         if (this === other) return true
80         if (other == null || this::class != other::class) return false
81 
82         other as CombinedLoadStates
83 
84         if (refresh != other.refresh) return false
85         if (prepend != other.prepend) return false
86         if (append != other.append) return false
87         if (source != other.source) return false
88         if (mediator != other.mediator) return false
89 
90         return true
91     }
92 
93     override fun hashCode(): Int {
94         var result = refresh.hashCode()
95         result = 31 * result + prepend.hashCode()
96         result = 31 * result + append.hashCode()
97         result = 31 * result + source.hashCode()
98         result = 31 * result + (mediator?.hashCode() ?: 0)
99         return result
100     }
101 
102     override fun toString(): String {
103         return "CombinedLoadStates(refresh=$refresh, prepend=$prepend, append=$append, " +
104             "source=$source, mediator=$mediator)"
105     }
106 
107     internal fun forEach(op: (LoadType, Boolean, LoadState) -> Unit) {
108         source.forEach { type, state -> op(type, false, state) }
109         mediator?.forEach { type, state -> op(type, true, state) }
110     }
111 
112     /** Returns true when [source] and [mediator] is in [NotLoading] for all [LoadType] */
113     public val isIdle = source.isIdle && mediator?.isIdle ?: true
114 
115     /**
116      * Returns true if either [source] or [mediator] has a [LoadType] that is in [LoadState.Error]
117      */
118     @get:JvmName("hasError") public val hasError = source.hasError || mediator?.hasError ?: false
119 }
120 
121 /**
122  * Function to wait on a Flow<CombinedLoadStates> until a load has completed.
123  *
124  * It collects on the Flow<CombinedLoadStates> and suspends until it collects and returns the
125  * firstOrNull [CombinedLoadStates] where all [LoadStates] have settled into a non-loading state
126  * i.e. [LoadState.NotLoading] or [LoadState.Error].
127  *
128  * A use case could be scrolling to a position after refresh has completed:
129  * ```
130  * override fun onCreate(savedInstanceState: Bundle?) {
131  *     ...
132  *     refreshButton.setOnClickListener {
133  *         pagingAdapter.refresh()
134  *         lifecycleScope.launch {
135  *             // wait for refresh to complete
136  *             pagingAdapter.loadStateFlow.awaitNotLoading()
137  *             // do work after refresh
138  *             recyclerView.scrollToPosition(position)
139  *         }
140  *    }
141  * }
142  * ```
143  */
144 @OptIn(FlowPreview::class)
awaitNotLoadingnull145 public suspend fun Flow<CombinedLoadStates>.awaitNotLoading():
146     @JvmSuppressWildcards CombinedLoadStates? {
147 
148     return debounce(1).filter { it.isIdle || it.hasError }.firstOrNull()
149 }
150