android - 因为 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 任务已被贬低,如何将我的代码更改为最新的请帮助我
解决方案
你可以使用协程,因为你已经在使用 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>
这就是你所做的一切。
推荐阅读
- html - 无法在自定义 Angular 元素上进行旋转
- javascript - InsertAfter 使用 Javascript 的长 HTML 块
- scala - Scala将元素添加到scala中的Nil列表
- sql - 当我执行更新表的过程时对象名称无效
- matlab - OpenCV中的匹配阈值过滤(Matlab转换)
- java - 错误:java:包 netscape.javascript 不存在
- python - 如何在每次执行 python 时导入模块?
- javascript - 在jquery中添加类
- mysql - 基于其结果的 mySQL SELECT
- reactjs - react-router-sitemap 不会为列表中的动态内容生成 url