如何简单地用RX/Coroutines替换android AsyncTask并返回一个值?

如何简单地用RX/Coroutines替换android AsyncTask并返回一个值?,android,android-asynctask,rx-java2,android-room,kotlin-coroutines,Android,Android Asynctask,Rx Java2,Android Room,Kotlin Coroutines,此方法运行数据库操作(返回生成的ID),并且必须位于后台线程上: fun插入(注意:注意):长{ returnnotedao.insert(注释) } 是否有一种使用RX/协同程序实现它的方法?(不使用suspend关键字) 我目前使用AsyncTask: override fun insert(note: Note): Long { return InsertTask(this, noteDao).execute(note).get() } private类InsertTask(no

此方法运行数据库操作(返回生成的ID),并且必须位于后台线程上:

fun插入(注意:注意):长{
returnnotedao.insert(注释)
}

是否有一种使用RX/协同程序实现它的方法?(不使用
suspend
关键字)

我目前使用AsyncTask:

override fun insert(note: Note): Long {
    return InsertTask(this, noteDao).execute(note).get()
}
private类InsertTask(noteRepository:noteRepository,private val noteDao:noteDao):AsyncTask(){


使用协同程序非常简单。但是您需要对
Room
提供协同程序支持

渐变依赖性:

implementation "androidx.room:room-ktx:2.1.0"
接下来,将dao中的方法标记为suspend

@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,因此请参阅。

我需要一个带有返回值的示例。如前所述,我对
suspend
关键字不感兴趣,即使这样使用它,我也会遇到编译错误。Rx链接看起来很有希望:)谢谢!它与返回值的效果相同,其中可能有差异,无法返回val从
launch
withContext
中返回。您不需要从launch或withContext返回值,该值将作为简单的迭代编程指令返回。
val a=returnMethod()
。这就是为什么我告诉你,在使用协同程序之前,你需要先处理好协同程序的基础知识。显然你一直都是对的。我只是对协同程序理解不够,无法理解你的答案,这很好:)那么应该是Rx,还是协同程序?两者都可能,但我找到并编写了Rx解决方案。
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)
  }
}