I’m trying to add a new feature to a compose sample project (list of posts), on which I need to call a new web service that fetches the posts based on a tag.
To implement this feature I thought about adding a new PagingSource PostByTagPagingSource
that call the getPostByTagUseCase.invoke(postId, nextPage))
when the user tries to search by tag, change the uiState
to the newly created Pager
that use another PagingSuurce.
Currently, the existing code is :
ViewModel
@HiltViewModel
class PostViewModel @Inject constructor(
postUseCase: GetPostUseCase) : ViewModel() {
var uiState: Flow<PagingData<PostModel>> =
Pager(
config = PagingConfig(
pageSize = ITEMS_PER_PAGE,
enablePlaceholders = true
),
pagingSourceFactory = {
PostPagingSource(
postUseCase // postUseCase call getPostUseCase.invoke(nextPage)
)
}
).flow.cachedIn(viewModelScope)
Compose side :
val lazyPagingPosts = viewModel.uiState.collectAsLazyPagingItems()
After update :
@HiltViewModel
class PostViewModel @Inject constructor(
postUseCase: GetPostUseCase, private val postByTagUseCase : GetPostByTagUseCase
) : ViewModel() {
var uiState: Flow<PagingData<PostModel>> =
Pager(
config = PagingConfig(
pageSize = ITEMS_PER_PAGE,
enablePlaceholders = true
),
pagingSourceFactory = {
PostPagingSource(
postUseCase
)
}
).flow.cachedIn(viewModelScope)
fun getPostByTag(tagId : String) {
uiState = Pager(
config = PagingConfig(
pageSize = ITEMS_PER_PAGE,
enablePlaceholders = true
),
pagingSourceFactory = {
PostByTagPagingSource(postByTagUseCase, tagId)
}
).flow.cachedIn(viewModelScope)
}
}
Compose side :
TagEditableUserInput(
hint = "Choose tag",
caption = "To",
vectorImageId = R.drawable.search,
onInputChanged = {
viewModel.getPostByTag(it)
}
)
This current draft implementation works but after scrolling and it’s not the proper.