【问题标题】:How to simply replace android AsyncTask with RX / Coroutines and return a value?如何简单地用 RX / Coroutines 替换 android AsyncTask 并返回一个值?
【发布时间】:2019-07-11 07:36:05
【问题描述】:

此方法运行数据库操作(返回生成的 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
    }
}

【问题讨论】:

  • 那么应该是Rx,还是协程?
  • 两者都可能,但我找到并编写了 Rx 解决方案。

标签: android android-asynctask rx-java2 android-room kotlin-coroutines


【解决方案1】:

使用协程,这很容易。但是您需要对 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

【讨论】:

  • 我需要一个带返回值的示例。如前所述,我对 suspend 关键字不感兴趣,即使像这样使用它,我也会遇到编译错误.. RX 链接看起来很有希望:) 谢谢!
  • 返回值也是一样的,区别在哪里
  • 无法从 launchwithContext 中返回 val。
  • 您不需要从launch 或withContext 返回值,该值将作为简单的迭代编程指令返回。 val a = returnMethod()。这就是为什么我告诉你,你需要在使用协程之前处理它们的基础知识。
  • 显然你一直都是对的。我只是对协程的理解不够理解你的答案,这很好:)
猜你喜欢
  • 2018-04-03
  • 1970-01-01
  • 1970-01-01
  • 2016-01-26
  • 2021-02-11
  • 2012-03-16
  • 1970-01-01
  • 2012-08-21
  • 1970-01-01
相关资源
最近更新 更多