Android

Android) Jetpack Compose에서 Paging 라이브러리 사용해보기

가짜 개발자 2021. 12. 4. 20:56


오늘은 Jetpack Compose에서 Paigng 라이브러리를 사용하는 예제를 구현해보려 합니다.

 

Compose With Paging

  • Paging 라이브러리를 사용해 서버로부터 데이터를 받아오는 코드는 기존의 구현 방법과 같습니다.
  • Composable 함수에서 데이터를 렌더링 하는 방법을 보겠습니다.
@Composable
fun PhotoList(mainViewModel: MainViewModel) {
    val photos = mainViewModel.getPhotoList().collectAsLazyPagingItems()
}
  • Compose에서 리사이클러뷰와 동일한 역할을 하는 LazyColumn에서 Flow<PagingData<T>>를 사용할 수 있도록 collectAsLazyPagingItems 확장 함수를 사용하여 변환합니다.
  • Compose는 리사이클러뷰 구현에 있어 굉장한 코드의 감소가 느껴집니다.
@Composable
public fun <T : Any> Flow<PagingData<T>>.collectAsLazyPagingItems(): LazyPagingItems<T> {
   ..
}
  • collectAsLazyPagingItemsLazyPagingItems<T>를 리턴합니다.
  • 그다음 LazyColumn items를 사용해 보여줄 리스트를 추가합니다.
LazyColumn(modifier = Modifier.fillMaxSize()) {
      items(photos.itemCount) { item ->
          photos[item]?.let { photo -> PhotoCard(photo = photo) }
      }
  • Coil 라이브러리를 사용해 서버에서 받아온 이미지를 로딩합니다.
  • rememberImagePainter 함수는 Composable에서 이미지를 그릴 수 있는 ImagePainter를 만듭니다.
  • ImagePainter는 비동기 이미지 요청과 placeholder/success/error 등을 관리해주는 역할을 합니다. 
  • 이미지를 렌더링 하는 state에 따라 분기 처리하여 코드를 처리할 수 있습니다.
val painter = rememberImagePainter(data = photo.downloadUrl, builder = {
                crossfade(true)
            })
            
Box {
        Image(
            painter = painter,
            contentDescription = null,
            modifier = Modifier.size(120.dp),
            contentScale = ContentScale.Crop
        )

        when (painter.state) {
            is ImagePainter.State.Loading -> {
                // Display a circular progress indicator whilst loading
                CircularProgressIndicator(Modifier.align(Alignment.Center))
            }
            is ImagePainter.State.Error -> {
                // If you wish to display some content if the request fails
            }
        }
    }
  • 기존의 페이징 라이브러리에서 데이터의 loadState에 따라 분기 처리할 수 있는 코드들도 제공하고 있습니다.
  • 또한, CircularProgressIndicator를 통해 쉽게 progress bar의 역할을 구현할 수 있습니다.
photos.apply {
    when {
        loadState.refresh is LoadState.Loading -> item {
            showProgress()
        }
        loadState.append is LoadState.Loading -> {
            item { LoadingView(modifier = Modifier.fillParentMaxSize()) }
        }
        loadState.refresh is LoadState.Error -> {
            val e = photos.loadState.refresh as LoadState.Error
            item {
              ErrorScreen(
	            message = e.error.localizedMessage!!,
	            modifier = Modifier.fillParentMaxSize()
	          ) {
                    retry()
                 }
            }
        }
    }
}

@Composable
fun ShowProgressBar() {
    Box(modifier = Modifier.fullScreen(backgroundColor = Color.White)) {
        CircularProgressIndicator(
            color = Color.Red,
            modifier = Modifier.align(Alignment.Center)
        )
    }
}

 

Screen

  • 구현한 화면은 다음과 같습니다.

 

 


Preference

coil

Pagination in Jetpack Compose

반응형