如何简单地将 android AsyncTask 替换为 RX / Coroutines 和 return 一个值?
How to simply replace android AsyncTask with RX / Coroutines and return a value?
此方法运行数据库操作(returns 生成的 ID)并且必须在后台线程上:
fun insert(note: Note): Long{
return noteDao.insert(note)
}
有没有办法用RX/Coroutines来实现? (不使用 suspend
关键字)
我目前使用 AsyncTask:
override fun insert(note: Note): Long {
return InsertTask(this, noteDao).execute(note).get()
}
private class InsertTask(noteRepository: NoteRepository, private val noteDao: NoteDao) : AsyncTask<Note, Void, Long>() {
override fun doInBackground(vararg note: Note): Long {
return noteDao.insert(note[0])
}
override fun onPostExecute(generatedId: Long) {
getTheId(generatedId)
}
private fun getTheId( id: Long): Long {
return id
}
}
使用协程,这很容易。但是你需要 Room
.
的协程支持
Gradle 依赖关系:
implementation "androidx.room:room-ktx:2.1.0"
接下来,将您在dao 中的方法标记为挂起。
@Insert
suspend fun insert(note: Note): Long
我不知道你有多少关于协程的信息,但它是这样的:
aCoroutineScope.launch(Dispatchers.IO){
//to make analogy you are inside the do in backgroun here
val id = dao.insert(note)
withContext(Dispatchers.Main){
//oh well you can call this onPostExecute :)
//do whatever you need with that selectId here
handleIdOnTheMainThread(id)
}
}
但我坚持不使用它,关于协程的信息为 0。
关于 RxJava:
Room也支持Rx,请参考this link。
此方法运行数据库操作(returns 生成的 ID)并且必须在后台线程上:
fun insert(note: Note): Long{
return noteDao.insert(note)
}
有没有办法用RX/Coroutines来实现? (不使用 suspend
关键字)
我目前使用 AsyncTask:
override fun insert(note: Note): Long {
return InsertTask(this, noteDao).execute(note).get()
}
private class InsertTask(noteRepository: NoteRepository, private val noteDao: NoteDao) : AsyncTask<Note, Void, Long>() {
override fun doInBackground(vararg note: Note): Long {
return noteDao.insert(note[0])
}
override fun onPostExecute(generatedId: Long) {
getTheId(generatedId)
}
private fun getTheId( id: Long): Long {
return id
}
}
使用协程,这很容易。但是你需要 Room
.
Gradle 依赖关系:
implementation "androidx.room:room-ktx:2.1.0"
接下来,将您在dao 中的方法标记为挂起。
@Insert
suspend fun insert(note: Note): Long
我不知道你有多少关于协程的信息,但它是这样的:
aCoroutineScope.launch(Dispatchers.IO){
//to make analogy you are inside the do in backgroun here
val id = dao.insert(note)
withContext(Dispatchers.Main){
//oh well you can call this onPostExecute :)
//do whatever you need with that selectId here
handleIdOnTheMainThread(id)
}
}
但我坚持不使用它,关于协程的信息为 0。
关于 RxJava:
Room也支持Rx,请参考this link。