【问题标题】:Observe the Room database 'insert' callback观察房间数据库“插入”回调
【发布时间】:2020-07-31 16:46:24
【问题描述】:

我们如何将存储库中的“插入”操作的回调作为 Livedata,并且我可以使用协程传回视图模型?

道

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(user : User): Long 

【问题讨论】:

    标签: android mvvm android-room android-livedata


    【解决方案1】:

    如果您在代码中使用协程,我不确定是否需要回调。

    如果您将 insert 函数设为挂起,则可以从协程内部的 ViewModel 调用它(例如使用 viewModelScope)。在这个协程中,只有在完成insert 方法之后,您才会移动到下一行代码:

    viewModelScope.launch{
       val userId = repository.insert(someUser)
       // <- there coroutine is suspended until insert is done. In a sense it's like a callback
       someOtherMethod()   
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      相关资源
      最近更新 更多