/painless-paging-library

Android Paging Library with painless implementation

Primary LanguageKotlinApache License 2.0Apache-2.0

Painless Paging Library

bintray License Pull request Twitter Github

Android Paging Library with painless implementation
Build for modern architecture with Kotlin and Coroutine

Download

Step 1 - Add the JitPack repository to your build file

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

Step 2 - Add the dependency

dependencies {
     implementation 'com.github.utsmannn:painless-paging-library:1.1.0'
}

Implementation

Create Adapter

The adapter extend to PainlessPagedAdapter

// standard view holder
class UserViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    fun bind(item: User, position: Int) = itemView.run {
        findViewById<TextView>(R.id.txt_item).text = "$position - ${item.name}"
    }
}

// adapter with PainlessPagedAdapter
class UserAdapter : PainlessPagedAdapter<User, UserViewHolder>() {
    override fun onCreatePageViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
        return UserViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_view, parent, false))
    }

    override fun onBindPageViewHolder(holder: UserViewHolder, position: Int) {
        getItem(position)?.let {
            holder.bind(it, position)
        }
    }

}

Create data source

Create class with extend to PagingDataSource

class UserDataSource : PagingDataSource<User>() {
    private val userRepository: UserRepository = UserRepository.Companion.Impl()

    override suspend fun onLoadState(page: Int): PagingResult {
        return try {
            val response = userRepository.getUsers(page)
            val items = response.data
            PagingResult.Success(items ?: emptyList())
        } catch (e: Throwable) {
            PagingResult.Error(e)
        }
    }
}

Add in ViewModel

The data source will be extracting result item with PagingData class and wrapping with liveData, implement it on ViewModel.

class UserViewModel : ViewModel() {

    private val userDataSource = UserDataSource()
    val pageData: LiveData<PagingData<User>>
            get() = userDataSource.currentPageLiveData()
}

Submitting item on adapter

viewModel.pageData.observe(this) { pagingData ->
    userAdapter.submitData(pagingData)
}

Extensions

This library can generate adapter with simple extensions code. Not recommended for multiple view type adapter.

val userAdapter = recyclerView.createSimpleAdapter<User>(R.layout.item_view) {
    layoutManager = LinearLayoutManager(this@MainActivity)
    onBindViewHolder = { itemView, item, position ->
        itemView.run {
            findViewById<TextView>(R.id.txt_item).text = "$position - ${item.name}"
        }
    }
}

Add State changes UI

You can add the loading view in footer, state of data changes.

Create a standard view holder

Place all view when data change to loading and error

class StateViewHolder(view: View) : RecyclerView.ViewHolder(view) {

    fun bind(loadState: LoadState, retry: () -> Unit) = itemView.run {
        findViewById<ProgressBar>(R.id.progress_bar).run {
            isVisible = loadState.loadStatus == LoadStatus.RUNNING
        }

        findViewById<TextView>(R.id.txt_error).run {
            isVisible = loadState.loadStatus == LoadStatus.FAILED

            if (loadState.loadStatus == LoadStatus.FAILED) {
                text = (loadState as LoadState.Failed).throwable?.message
            }
        }

        findViewById<Button>(R.id.btn_retry).run {
            isVisible = loadState.loadStatus == LoadStatus.FAILED
            setOnClickListener {
                retry.invoke()
            }
        }
    }
}

Attach state view holder in adapter

userAdapter.attachStateViewHolder { parent  ->
    val view = LayoutInflater.from(parent.context).inflate(R.layout.state_view, parent, false)
    StateViewHolder(view)
}

userAdapter.onBindLoadStateViewHolder<StateViewHolder> { holder, loadState ->
    holder.bind(loadState) {
        userAdapter.retry()
    }
}

License

Copyright 2021 Muhammad Utsman

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.