首页 > 解决方案 > 因为 Aysnc 任务被贬低了我可以使用什么替代方案以及如何使用

问题描述

class FavouritesFragment : Fragment() {
lateinit var recyclerFavourite:RecyclerView
lateinit var progressLayout:RelativeLayout
lateinit var progressBar:ProgressBar
lateinit var layoutManager:RecyclerView.LayoutManager
lateinit var recyclerAdapter: FavouriteRecyclerAdapter
var dbBookList=listOf<BookEntity>()


override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    val view=inflater.inflate(R.layout.fragment_favourites, container, false)
    recyclerFavourite=view.findViewById(R.id.recyclerFavourite)
    progressLayout=view.findViewById(R.id.progressLayout)
    progressBar=view.findViewById(R.id.progressBar)
    layoutManager=GridLayoutManager(activity as Context,2)
    dbBookList=RetrieveFavourites(activity as Context).execute().get()
    if(activity!=null)
    {
        progressLayout.visibility=View.GONE
        recyclerAdapter= FavouriteRecyclerAdapter(activity as Context,dbBookList)
        recyclerFavourite.adapter=recyclerAdapter
        recyclerFavourite.layoutManager=layoutManager
    }
    return view
}
class RetrieveFavourites(val context: Context):AsyncTask<Void,Void,List<BookEntity>>()
{
    override fun doInBackground(vararg p0: Void?): List<BookEntity> {
        val db= Room.databaseBuilder(context,BookDatabase::class.java,"books-db").build()
        return db.bookDao().getAllBooks()
    }

}

}

上面的代码用于在单击“添加到收藏夹”按钮时将一本书添加到收藏夹数据库,现在由于 aysnc 任务已被贬低,如何将我的代码更改为最新的请帮助我

标签: androidandroid-asynctask

解决方案


你可以使用协程,因为你已经在使用 kotlin

这是一个可以帮助你的代码实验室

https://developer.android.com/codelabs/android-room-with-a-view-kotlin#0

codelab 显示了类似的用例,所以我认为我不必再发布片段了

附上一个简短的代码片段来展示协程是如何工作的

在 onViewCreated

viewLifecycleOwner.lifecycleScope.launch {
  db.bookDao().getAllBooks() 
}

在书道

在 getAllBooks() 方法之前使用暂停

suspend from getAllBooks(): List<Books>

这就是你所做的一切。


推荐阅读