如何观察PagedList数据?

时间:2017-11-06 05:00:10

标签: android kotlin android-architecture-components android-livedata android-viewmodel

我正在使用Paging Library和Android架构组件。我只想观察pagedlist livedata并在发生更改时更新我的​​RecyclerView。

我正在观察isLoadingLiveData,isEmptyLiveData和errorLiveData对象,这些对象是在我的ViewModel中创建并在我的片段中观察到的MediatorLiveData对象。并观察resultLiveData,它从远程返回获取的Gist列表。

在我的ViewModel中,我创建了一个PagedList LiveData,每当它的数据发生变化时,我想更新isLoadingLiveData,isEmptyLiveData,errorLiveData和PagedListAdapter。因此,我将isLoadingLiveData,isEmptyLiveData,errorLiveData和resultLiveData定义为MediatorLiveData对象。我添加了resultLiveData作为这些对象的源。所以当resultLiveData发生变化时,这些对象就会出现。将调用onChanged方法。 resultLiveData依赖于userNameLiveData,因此当userNameLiveData发生更改时,将调用allGistsLiveData并获取数据。例如,当用户滑动列表时,我设置了userNameLiveData并再次进行网络呼叫。

我的ViewModel:

private val userNameLiveData = MutableLiveData<String>()
private var gists: LiveData<PagedList<Gist>>? = null

val allGistsLiveData: LiveData<PagedList<Gist>>
    get() {
        if (null == gists) {
            gists = GistModel(NetManager(getApplication()), getApplication()).getYourGists(userNameLiveData.value!!).create(0,
                    PagedList.Config.Builder()
                            .setPageSize(PAGED_LIST_PAGE_SIZE)
                            .setInitialLoadSizeHint(PAGED_LIST_PAGE_SIZE)
                            .setEnablePlaceholders(PAGED_LIST_ENABLE_PLACEHOLDERS)
                            .build())
        }
        return gists!!
    }

val resultLiveData = MediatorLiveData<LiveData<PagedList<Gist>>>().apply {
    this.addSource(userNameLiveData) {
        gists = null
        this.value = allGistsLiveData
    }
}


val isLoadingLiveData = MediatorLiveData<Boolean>().apply {
    this.addSource(resultLiveData) { this.value = false }
}

val isEmptyLiveData = MediatorLiveData<Boolean>().apply {
    this.addSource(resultLiveData) { this.value = false }
}

val errorLiveData = MediatorLiveData<Boolean>().apply {
    this.addSource(resultLiveData) {
        if (it == null) {
            this.value = true
        }
    }
}

fun setUserName(userName: String) {
    userNameLiveData.value = userName
}

和我的片段:

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    viewModel.isEmptyLiveData.observe(this@YourGistsFragment, Observer<Boolean> { isVisible ->
        emptyView.visibility = if (isVisible!!) View.VISIBLE else View.GONE
    })

    viewModel.isLoadingLiveData.observe(this@YourGistsFragment, Observer<Boolean> {
        it?.let {
            swipeRefreshLayout.isRefreshing = it
        }
    })

    viewModel.errorLiveData.observe(this@YourGistsFragment, Observer<Boolean> {
        it?.let {
            showSnackBar(context.getString(R.string.unknown_error))
        }
    })

    viewModel.setUserName("melomg")
    viewModel.resultLiveData.observe(this@YourGistsFragment, Observer { it -> gistAdapter.setList(it?.value) })
}


override fun onRefresh() {
    viewModel.setUserName("melomg")
}

我的存储库:

fun getYourGists(userName: String): LivePagedListProvider<Int, Gist> {
    return remoteDataSource.getYourGists(userName, GitHubApi.getGitHubService(context))
}

我的remoteDataSource:

fun getYourGists(username: String, dataProvider: GitHubService): LivePagedListProvider<Int, Gist> {
    return object : LivePagedListProvider<Int, Gist>() {
        override fun createDataSource(): GistTiledRemoteDataSource<Gist> = object : GistTiledRemoteDataSource<Gist>(username, dataProvider) {
            override fun convertToItems(items: ArrayList<Gist>?): ArrayList<Gist>? {
                return items
            }
        }
    }
}

我尝试从this project创建此解决方案。但我的问题是 resultLiveData一直在变化而不等待网络呼叫响应,因此忽略了响应的结果,并且在数据到达之前我的ui正在更新。由于resultLiveData在请求之前发生变化,因此还没有数据。我怎么能观察pagedlist livedata?

2 个答案:

答案 0 :(得分:0)

最后,我找到了一个有效的解决方案,但我认为这不是最好的解决方案。所以,如果您有任何想法,请不要犹豫,回答。这是我的解决方案:

我放弃了使用PagedList包装MediatorLiveData数据。我仍将我的所有其他实时数据(isLoadingLiveData, isEmptyLiveData, errorLiveData)保留为MediatorLiveData,但在我的gist PagedList LiveData初始化时添加了他们的来源。这是代码:

private var gists: LiveData<PagedList<Gist>>? = null
private val userNameLiveData = MutableLiveData<String>()
val isLoadingLiveData = MediatorLiveData<Boolean>()
val isEmptyLiveData = MediatorLiveData<Boolean>()
val errorLiveData = MediatorLiveData<ErrorMessage>()

val allGistsLiveData: LiveData<PagedList<Gist>>
    get() {
        if (gists == null) {
                gists = GistModel(NetManager(getApplication()), getApplication()).getYourGists(userNameLiveData.value!!).create(0,
                        PagedList.Config.Builder()
                                .setPageSize(Constants.PAGED_LIST_PAGE_SIZE)
                                .setInitialLoadSizeHint(Constants.PAGED_LIST_PAGE_SIZE)
                                .setEnablePlaceholders(Constants.PAGED_LIST_ENABLE_PLACEHOLDERS)
                                .build())


                isLoadingLiveData.addSource(gists) { isLoadingLiveData.value = false }
                isEmptyLiveData.addSource(gists) {
                    if (it?.size == 0) {
                        isEmptyLiveData.value = true
                    }
                }
                errorLiveData.addSource(gists) {
                    if (it == null) {
                        errorLiveData.value = ErrorMessage(errorCode = ErrorCode.GENERAL_ERROR)
                    }
                }
            }
        }
        return gists!!
    }


fun setUserName(userName: String) {
    isLoadingLiveData.value = true
    userNameLiveData.value = userName
    gists = null
    allGistsLiveData
}

答案 1 :(得分:0)

有一个更好的方法可以做到这一点。看这个例子:

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

诀窍是将可变的实时数据放入数据源,如下所示:

enum class NetworkState { LOADING, LOADED, FAILURE }

val networkState = MutableLiveData<NetworkState>()

override fun loadInitial(params: LoadInitialParams<String>, callback: LoadInitialCallback<String,  OrderService.Resource>) {
    networkState.post(NetworkState.LOADING)
    ApiClient.listMyObjects(
            onSuccess = { list ->
                networkState.post(NetworkState.LOADED)
                callback.onResult(list)
            }
            onFailure = {
                networkState.post(NetworkState.FAILURE)
            }
    )
}

然后,您可以使用以下方法收听分页列表和网络状态:

val myDataSource = MyDataSource.Factory().create()
myDataSource.toLiveData().observe(viewLifeCycle, Observer { pagedList ->
    // Update your recycler view
    myRecyclerViewAdapter.submitList(pagedList)
})
myDataSource.networkState.observe(viewLifeCycle, Observer { state ->
    // Show errors, retry button, progress view etc. according to state  
})