[Android/Compose] Paging 사용하여 무한스크롤 구현하기

찌니·2022년 9월 27일
2

Android(Compose)

목록 보기
4/12
post-thumbnail

이번 프로젝트에서 시간을 가장 많이 들인 paging,,, 이정도로 오래걸릴 일이 아닌데 엄청나게 삽질했다ㅜㅡㅠ
db module 통신으로 데이터를 가져오는 paging을 구현했습니다 많은 부분에서 부족하니 이해해주세요!!

PagingSource

private const val STARTING_PAGE_INDEX = 1

class MyPagingSource(
    private val reqPostData: ReqPostData
): PagingSource<Int, PostData>() {
    private val dbAccessModule = DBAccessModule()
    // 스크롤시 데이터를 비동기식으로 가져오기 위한 함수
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, PostData> {
        // LoadParams: 로드할 키와 항목 수, LoadResult: 로드 작업의 결과
        try {
            val position = params.key?: STARTING_PAGE_INDEX
            val result = dbAccessModule.getPostOrderByTime(page = position,reqPostData = reqPostData)
            return if (result != emptyList<PostData>()){
                LoadResult.Page(
                    data = result,
                    prevKey = when(position){
                        STARTING_PAGE_INDEX -> null
                        else -> position -1 },
                    nextKey = position + 1
                )
            }else{
                LoadResult.Invalid() // PagingSource가 더 이상 결과의 무결성을 보장할 수 없으므로 무효화되어야 하는 경우
        } catch (exception: IOException) {
            return LoadResult.Error(exception)
        }


    }
    override fun getRefreshKey(state: PagingState<Int, PostData>): Int? {
        return state.anchorPosition
    }

}

ViewModel

 var sharePostsByTime = Pager(
             PagingConfig(pageSize = 10))
         { MyPagingSource(initData.value)
             }.flow.cachedIn(viewModelScope)

View

 // 생략
	SharePostListByTime(postItems = postViewModel.sharePostsByTime.collectAsLazyPagingItems())
}

@Composable
fun SharePostListByTime(postItems: LazyPagingItems<PostData>){
    LazyColumn(
        userScrollEnabled = true,
        modifier = Modifier
            .background(Color.White)
    ) {
        items(posts){ post ->
            ItemCardByTime(post= post)
        }
    }
}

지금보니 세상 간단ㅠㅡㅜ 이해하는데 꽤나 오래걸렸는데 정말 오래걸릴 일이 아니엿다고 한다..
하지만 이것도 성장..^^ 이라고 할 수 있지 않을까나

profile
찌니's develog

0개의 댓글