我正在尝试使用LiveData从Room数据库中分页数据。 Google的示例代码表明使用了toLiveData函数:

class ConcertViewModel(concertDao: ConcertDao) : ViewModel() {
    val concertList: LiveData<PagedList<Concert>> =
            concertDao.concertsByDate().toLiveData(pageSize = 50)
}

https://developer.android.com/topic/libraries/architecture/paging

这是我创建的遵循其示例的代码:

AppDao.kt
import androidx.lifecycle.LiveData
import androidx.paging.DataSource
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy.REPLACE
import androidx.room.Query
import com.example.model.UserConnection

@Dao
interface AppDao {
    @Query("SELECT * FROM UserConnection")
    fun getAll(): LiveData<List<UserConnection>>

    @Insert(onConflict = REPLACE)
    fun save(userConnection: UserConnection)

    @Query("SELECT * FROM UserConnection ORDER BY firstName DESC")
    fun connectionsByFirstName(): DataSource.Factory<Int, UserConnection>
}

AppDatabase.kt
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.example.model.UserConnection

@Database(entities = arrayOf(UserConnection::class), version = 1, exportSchema = true)
@TypeConverters(RoomConverters::class)
abstract class AppDatabase : RoomDatabase() {
    abstract fun appDao(): AppDao
}

ConnectionsViewModel.kt
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.paging.DataSource
import androidx.paging.PagedList
import com.linkedintools.da.local.room.AppDao
import com.example.model.UserConnection
import javax.inject.Inject

class ConnectionsViewModel @Inject constructor(appDao: AppDao) : ViewModel() {

    val connectionsDataSource : DataSource.Factory<Int, UserConnection> = appDao.connectionsByFirstName()

    val concertList: LiveData<PagedList<UserConnection>> = connectionsDataSource.toLiveData(pageSize = 40)

}

build.gradle
dependencies {
    def room_version = "2.1.0-rc01"
    def paging_version = "2.1.0"

    implementation "androidx.room:room-runtime:$room_version"
    kapt "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor

    // optional - Kotlin Extensions and Coroutines support for Room
    implementation "androidx.room:room-ktx:$room_version"

    // optional - RxJava support for Room
    implementation "androidx.room:room-rxjava2:$room_version"

    // Paging
    implementation "androidx.paging:paging-runtime:$paging_version"

}

toLiveData不可用。我做错什么了吗?还是Google的示例代码已经过时了?

最佳答案

toLiveData 是一种扩展乐趣,导入该库就可以了:
androidx.paging:paging-runtime-ktx:2.1.0-rc01

另外检查此Google样本项目Paging With Network Sample

https://github.com/googlesamples/android-architecture-components/tree/master/PagingWithNetworkSample

09-12 04:20