Compose中使用paging3进行列表分页加载Room中的数据

一、前言

本文简要记录下流程,代码需要修改后才可以运行

二、相关依赖

<project>/build.gradle

buildscript {
   
    ext {
   
        compose_version = '1.5.4'
    }
}// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
   
    id 'com.android.application' version '8.2.1' apply false
    id 'com.android.library' version '8.2.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.9.22' apply false
}

app/build.gradle

plugins {
   
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

android {
   
    compileSdk 34

    defaultConfig {
   
        applicationId "com.design.compose"
        minSdk 21
        targetSdk 34
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
   
            useSupportLibrary true
        }
    }

    buildTypes {
   
        release {
   
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
   
        sourceCompatibility JavaVersion.VERSION_18
        targetCompatibility JavaVersion.VERSION_18
    }
    kotlinOptions {
   
        jvmTarget = JavaVersion.VERSION_18
    }
    buildFeatures {
   
        compose true
    }
    composeOptions {
   
        kotlinCompilerExtensionVersion "1.5.8"
        kotlinCompilerVersion "1.9.22"
    }
    packagingOptions {
   
        resources {
   
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }

    namespace 'com.design.compose'
}

dependencies {
   

    implementation 'androidx.core:core-ktx:1.12.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.material3:material3"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.6.2")

    implementation("androidx.activity:activity-compose:1.8.1")
    implementation(platform("androidx.compose:compose-bom:2023.03.00"))
    implementation("androidx.compose.ui:ui")
    implementation("androidx.compose.ui:ui-graphics")
    implementation("androidx.compose.ui:ui-tooling-preview")

    implementation "androidx.paging:paging-compose:3.2.1"
//    该依赖需要target为34,可以使用androidx.paging:paging-compose进行替代
//    implementation "androidx.paging:paging-compose-android:3.3.0-alpha02"
    implementation "androidx.paging:paging-runtime-ktx:3.2.1"
    implementation "androidx.paging:paging-common-ktx:3.2.1"
    implementation "androidx.room:room-paging:2.6.1"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.2'
    implementation 'androidx.activity:activity-compose:1.8.1'
    kapt("androidx.room:room-compiler:2.6.1")
    implementation("androidx.room:room-runtime:2.6.1")
    implementation("androidx.room:room-ktx:2.6.1")
    implementation("androidx.room:room-paging:2.4.2")
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
    debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_version"
}

二、具体代码

@Parcelize
@Entity(tableName = "user_table")
data class UserInfo(
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    var id: Long = 0L,

    @ColumnInfo(name = "name")
    var name: String = "",
): Parcelable

@Dao
interface UserDao {
   
    @Query("SELECT * FROM user_table")
    fun getAllPagingSource(): PagingSource<Int, UserInfo>
    
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(list: List<UserInfo>)
    
    @Delete
    fun deleteAll(list: List<UserInfo>)
}
@Database(entities = [UserInfo::class,], version = 1, exportSchema = true)
abstract class DatabaseManager : RoomDatabase() {
   
    abstract fun getUserDao(): User

    companion object {
   
        private const val DATABASE_NAME = "user.db"

        private val instance by lazy {
   
            Room.databaseBuilder(App.getInstance(), DatabaseManager::class.java, DATABASE_NAME).build()
        }

        private fun getUserDao(): AlertDao {
   
            return instance.getUserDao()
        }
         fun getUserAllPagingSource(): PagingSource<Int,UserInfo>{
   
            return getAlertAreaDao().getAllPagingSource()
        }
    }
}

ViewModel

class UserModel : ViewModel(){
   
    val action = MutableLiveData<Action>()
    val singlePageSize = 10 //每页显示为10条

    fun loadRoomData(): PagingSource<Int, UserInfo> {
   
        return DatabaseManager.getUserAllPagingSource()
    }

    fun sendAction(action: Action) {
   
        this.action.value = action
    }

    sealed class Action {
   
        object BACK : Action()
        object ADD : Action()
        data class DETAILS(val info: UserInfo) : Action()
    }
}

UI

...
@Composable
    fun Center(modifier: Modifier = Modifier, viewModel: UserModel = viewModel()) {
   
        val pager = remember {
   
            Pager(
                PagingConfig(
                    pageSize = viewModel.singlePageSize,
                    enablePlaceholders = true,
//                    maxSize = 200
                )
            ) {
    viewModel.loadRoomData() }
        }

        val lazyPagingItems = pager.flow.map {
   
            it.map {
    info ->
                info.name = "${
     info.name}-->后缀"
//                Log.e("YM--->", "--->区域时间:${info.areaCreateTime}")
            }
            it
        }.collectAsLazyPagingItems()

        LazyColumn(modifier = modifier) {
   
            if (lazyPagingItems.itemCount == 0) {
   
                item(key = "defaultItem", contentType = "defaultItem") {
   
                    DefaultUserItem()
                }
            }

            items(count = lazyPagingItems.itemCount) {
    index ->
                val item = lazyPagingItems[index]
                if (item != null) {
   
                    UserItem(
                        modifier = Modifier.clickable(// 去除点击效果
                            indication = null,
                            interactionSource = remember {
   
                                MutableInteractionSource()
                            }) {
   
                            viewModel.sendAction(UserModel.Action.DETAILS(item))
                        },
                        info = item
                    )
                }
            }

            if (lazyPagingItems.loadState.append == LoadState.Loading) {
   
                item(key = "loadItem", contentType = "loadItem") {
   
                    CircularProgressIndicator(
                        modifier = Modifier
                            .fillMaxWidth()
                            .wrapContentWidth(Alignment.CenterHorizontally)
                    )
                }
            }

        }
    }

...

三、参考链接

  1. androidx.paging.compose
  2. Paging 库概览

最近更新

  1. TCP协议是安全的吗?

    2024-01-12 21:20:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-12 21:20:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-12 21:20:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-12 21:20:03       18 阅读

热门阅读

  1. 数据库-列的类型-字符串char类型

    2024-01-12 21:20:03       37 阅读
  2. redis前缀匹配数据迁移数据

    2024-01-12 21:20:03       36 阅读
  3. redis 面试题(二)

    2024-01-12 21:20:03       26 阅读
  4. DAC模块(MCP44725芯片)

    2024-01-12 21:20:03       40 阅读
  5. linux权限

    2024-01-12 21:20:03       32 阅读
  6. golang文件内容覆盖问题

    2024-01-12 21:20:03       34 阅读
  7. 安卓fragment监听文本内容取值

    2024-01-12 21:20:03       39 阅读
  8. C++基础之关键字——virtual详解

    2024-01-12 21:20:03       33 阅读
  9. 区块链知识学习(一)

    2024-01-12 21:20:03       32 阅读
  10. docker run命令

    2024-01-12 21:20:03       34 阅读