aboutsummaryrefslogtreecommitdiff
path: root/paging/common/src/main/kotlin/androidx/paging/PageFetcher.kt
blob: 17a7245a41d41a4d246cc60a74dc16d3361bcd9f (plain)
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
67
68
69
70
71
72
73
74
75
76
77
78
/*
 * Copyright 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package androidx.paging

import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.scan

@UseExperimental(ExperimentalCoroutinesApi::class)
internal class PageFetcher<Key : Any, Value : Any>(
    private val pagingSourceFactory: () -> PagingSource<Key, Value>,
    private val initialKey: Key?,
    private val config: PagingConfig
) {
    // NOTE: This channel is conflated, which means it has a buffer size of 1, and will always
    // broadcast the latest value received.
    private var refreshChannel = ConflatedBroadcastChannel<Unit>()

    // The object built by paging builder can maintain the scope so that on rotation we don't stop
    // the paging.
    @UseExperimental(FlowPreview::class)
    val flow = refreshChannel
        .asFlow()
        .onStart { emit(Unit) }
        .scan(null) { previousGeneration: Pager<Key, Value>?, _ ->
            val pagingSource = pagingSourceFactory()
            val initialKey = when (previousGeneration) {
                null -> initialKey
                else -> when (val info = previousGeneration.refreshKeyInfo()) {
                    null -> previousGeneration.initialKey
                    else -> pagingSource.getRefreshKeyFromPage(info.indexInPage, info.page)
                }
            }

            // Hook up refresh signals from DataSource / PagingSource.
            pagingSource.registerInvalidatedCallback(::refresh)
            previousGeneration?.pagingSource?.unregisterInvalidatedCallback(::refresh)
            previousGeneration?.pagingSource?.invalidate() // Note: Invalidate is idempotent.

            Pager(initialKey, pagingSource, config)
        }
        .filterNotNull()
        .mapLatest { generation ->
            PagingData(generation.pageEventFlow, PagerUiReceiver(generation))
        }

    fun refresh() {
        refreshChannel.offer(Unit)
    }
}

@UseExperimental(ExperimentalCoroutinesApi::class, FlowPreview::class)
internal class PagerUiReceiver<Key : Any, Value : Any> constructor(
    private val pager: Pager<Key, Value>
) : UiReceiver {
    override fun addHint(hint: ViewportHint) = pager.addHint(hint)

    override fun retry() = pager.retry()
}