A solution for efficient paging in Kotlin Multiplatform projects.
- Prioritizes extensibility with support for custom middleware, reducers, post-reducer effects, paging strategies, and data sources
- Supports delegating to Store for optimized data loading and caching
- Opens up mutations and streaming of child items within the list of paging items
- Includes built-in hooks for logging and error handling
- Uses a modular architecture with unidirectional data flow to make it easier to reason about and maintain
Add the following dependency to your project:
dependencies {
implementation("org.mobilenativefoundation.storex:storex-paging-core:1.0.0")
}
val pagingConfig = PagingConfig(
pageSize = 20,
prefetchDistance = 10,
insertionStrategy = InsertionStrategy.APPEND
)
val pagingSource = DefaultPagingSource(
streamProvider = store.pagingSourceStreamProvider(keyFactory)
)
val pager = PagerBuilder<MyId, MyKey, MyParams, MyData, MyCustomError, MyCustomAction>(
initialKey = PagingKey(key = 1, params = MyParams()),
anchorPosition = anchorPositionFlow,
)
.pagingConfig(pagingConfig)
.pagerBufferMaxSize(100)
// Provide a custom paging source
.pagingSource(MyCustomPagingSource())
// Or, use the default paging source
.defaultPagingSource(MyPagingSourceStreamProvider())
// Or, use Store as your paging source
.mutableStorePagingSource(mutableStore)
// Use the default reducer
.defaultReducer {
errorHandlingStrategy(ErrorHandlingStrategy.RetryLast(3))
customActionReducer(MyCustomActionReducer())
}
// Or, provide a custom reducer
.reducer(MyCustomReducer())
// Add custom middleware
.middleware(MyCustomMiddleware1())
.middleware(MyCustomMiddleware2())
// Add custom post-reducer effects
.effect<SomePagingAction, SomePagingState>(
action = SomePagingAction::class,
state = SomePagingState::class,
effect = MyCustomEffect1()
)
.effect<SomePagingAction, SomePagingState>(
action = SomePagingAction::class,
state = SomePagingState::class,
effect = MyCustomEffect2()
)
// Use the default logger
.defaultLogger()
.build()
pager.state.collect { state ->
when (state) {
is PagingState.Loading -> {
// Show loading indicator
InitialLoadingView()
}
is PagingState.Data.Idle -> {
// Update UI with loaded data
DataView(pagingItems = state.data) { action ->
pager.dispatch(action)
}
}
is PagingState.Error -> {
// Handle error state
ErrorViewCoordinator(errorState = state) { action ->
pager.dispatch(action)
}
}
}
}
typealias Id = MyId
typealias K = MyKey
typealias P = MyParams
typealias D = MyData
typealias E = MyCustomError
typealias A = MyCustomAction
1. Built-In Error Handling: You can configure error handling strategy using the errorHandlingStrategy
function when building the pager.
val pager = PagerBuilder<Id, K, P, D, E, A>(
scope,
initialKey,
initialState,
anchorPosition
)
.defaultReducer {
// Retry without emitting the error
errorHandlingStrategy(ErrorHandlingStrategy.RetryLast(3))
// Emit the error
errorHandlingStrategy(ErrorHandlingStrategy.PassThrough)
// Ignore the error
errorHandlingStrategy(ErrorHandlingStrategy.Ignore)
}
sealed class CustomError {
data class Enriched(
val throwable: Throwable,
val context: CustomContext
) : CustomError()
}
class ErrorEnrichingMiddleware(
private val contextProvider: CustomContextProvider
) : Middleware<Id, K, P, D, E, A> {
override suspend fun apply(
action: PagingAction<Id, K, P, D, E, A>,
next: suspend (PagingAction<Id, K, P, D, E, A>) -> Unit
) {
if (action is PagingAction.UpdateError) {
val modifiedError = CustomError.Enriched(action.error, contextProvider.requireContext())
next(action.copy(error = modifiedError))
} else {
next(action)
}
}
}
val pager = PagerBuilder<Id, K, P, D, E, A>(
scope,
initialKey,
initialState,
anchorPosition
)
.middleware(ErrorEnrichingMiddleware(contextProvider))
class ErrorLoggingEffect(private val logger: Logger) :
Effect<Id, K, P, D, E, A, PagingAction.UpdateError<Id, K, P, D, E, A>, PagingState.Error.Exception<Id, K, P, D, E>> {
override fun invoke(
action: PagingAction.UpdateError<Id, K, P, D, E, A>,
state: PagingState.Error.Exception<Id, K, P, D, E>,
dispatch: (PagingAction<Id, K, P, D, E, A>) -> Unit
) {
when (val error = action.error) {
is PagingSource.LoadResult.Error.Custom -> {}
is PagingSource.LoadResult.Error.Exception -> {
logger.log(error)
}
}
}
}
val pager = PagerBuilder<Id, K, P, D, E, A>(
scope,
initialKey,
initialState,
anchorPosition
)
.effect(PagingAction.UpdateError::class, PagingState.Error.Exception::class, errorLoggingEffect)
sealed interface MyCustomAction {
data object ClearData : TimelineAction
}
class MyCustomActionReducer : UserCustomActionReducer<Id, K, P, D, E, A> {
override fun reduce(action: PagingAction.User.Custom<Id, K, P, D, E, A>, state: PagingState<Id, K, P, D, E>): PagingState<Id, K, P, D, E> {
return when (action.action) {
MyCustomAction.ClearData -> {
when (state) {
is PagingState.Data.ErrorLoadingMore<Id, K, P, D, E, *> -> state.copy(data = emptyList())
is PagingState.Data.Idle -> state.copy(data = emptyList())
is PagingState.Data.LoadingMore -> state.copy(data = emptyList())
is PagingState.Error.Custom,
is PagingState.Error.Exception,
is PagingState.Initial,
is PagingState.Loading -> state
}
}
}
}
}
val pager = PagerBuilder<Id, K, P, D, E, A>(
scope,
initialKey,
initialState,
anchorPosition
)
.defaultReducer {
customActionReducer(MyCustomActionReducer())
}
class AuthMiddleware(private val authTokenProvider: () -> String) : Middleware<Id, K, P, D, E, A> {
private fun setAuthToken(headers: MutableMap<String, String>) = headers.apply {
this["auth"] = authTokenProvider()
}
override suspend fun apply(action: PagingAction<Id, K, P, D, E, A>, next: suspend (PagingAction<Id, K, P, D, E, A>) -> Unit) {
when (action) {
is PagingAction.User.Load -> {
setAuthToken(action.key.params.headers)
next(action)
}
is PagingAction.Load -> {
setAuthToken(action.key.params.headers)
next(action)
}
else -> next(action)
}
}
}
val pager = PagerBuilder<Id, K, P, D, E, A>(
scope,
initialKey,
initialState,
anchorPosition
)
.middleware(AuthMiddleware(authTokenProvider))
See the Custom Effects section under Handling Errors.
Copyright 2024 Mobile Native Foundation
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.