Skip to main content

PagingState<T>

Data class for managing paginated list state in ViewModels.

Module: :ui-state

Definition

data class PagingState<T>(
val items: List<T> = emptyList(),
val currentPage: Int = 1,
val isLoading: Boolean = false,
val hasMore: Boolean = true,
val error: String? = null
)

Properties

PropertyTypeDescription
itemsList<T>All loaded items
currentPageIntCurrent page number
isLoadingBooleanWhether a page is being loaded
hasMoreBooleanWhether more pages are available
errorString?Error message if last load failed

Operations

appendItems

Add items from a new page:

setState { copy(paging = paging.appendItems(newPosts)) }

refresh

Replace all items (pull-to-refresh):

setState { copy(paging = paging.refresh(freshPosts)) }

Example

data class FeedState(
val paging: PagingState<Post> = PagingState()
)

class FeedViewModel(
private val getPostsUseCase: GetPostsUseCase
) : BaseViewModel<FeedState, FeedEvent>(FeedState()) {

fun loadNextPage() = execute(
call = { getPostsUseCase(page = currentState.paging.currentPage) },
onLoading = { copy(paging = paging.copy(isLoading = true)) },
onSuccess = { posts ->
copy(paging = paging.appendItems(posts))
},
onError = { copy(paging = paging.copy(isLoading = false, error = it.message)) }
)

fun refresh() = execute(
call = { getPostsUseCase(page = 1) },
onSuccess = { posts ->
copy(paging = paging.refresh(posts))
}
)
}