扩展函数上的协程

jog*_*ghm 2 android kotlin kotlin-extension android-paging kotlin-coroutines

我正在使用扩展函数将列表数据绑定到 recyclerview ,使用 pagedlist 它不需要任何协程

@BindingAdapter("pagedListAdapterData")
fun <T : Any> submitPagedList(recyclerView: RecyclerView, list: PagedList<T>?) {
    if (list != null && recyclerView.adapter is PagedListAdapter<*, *>) {
        (recyclerView.adapter as? PagedListAdapter<T, RecyclerView.ViewHolder>)?.submitList((list))
    }
}

        pagedListAdapterData="@{viewModel.list}"
Run Code Online (Sandbox Code Playgroud)

但随着我升级到 Paging 3.0,它需要使用协程

@BindingAdapter("pagingDataAdapter")
fun <T : Any> submitPagingDataList(recyclerView: RecyclerView, list: PagingData<T>?) {
    if (list != null && recyclerView.adapter is PagingDataAdapter<*, *>) {
        GlobalScope.launch {
            (recyclerView.adapter as? PagingDataAdapter<T, RecyclerView.ViewHolder>)?.submitData((list))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这工作得很好,但我担心的是 Globalscope 的使用,似乎有更好的方法来做到这一点,因为不推荐 globalScope

Tor*_*ure 5

androidx.lifecycle有一个扩展函数View.findViewTreeLifecycleOwner,所以你不必创建自己的:

view.findViewTreeLifecycleOwner()?.lifecycleScope?.launch {
  ...
}
Run Code Online (Sandbox Code Playgroud)