GithubHelp home page GithubHelp logo

utsmannn / painless-paging-library Goto Github PK

View Code? Open in Web Editor NEW
10.0 2.0 2.0 209 KB

Android Paging Library with painless implementation

License: Apache License 2.0

Kotlin 100.00%
paging-library paging-library-in-android android-library paging3

painless-paging-library's Introduction

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:{latest_version}') {
        exclude group: 'com.google.android.material', module: 'material'
    }
}    
    

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.

painless-paging-library's People

Contributors

diigel avatar kucingapes avatar utsmannn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

painless-paging-library's Issues

Inconsistency detected

java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 10(offset:30).state:11 androidx.recyclerview.widget.RecyclerView

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.