观察会议室数据库的“插入”回调

时间:2020-07-31 16:46:24

标签: android mvvm android-room android-livedata

我们如何以Livedata的形式获取存储库中“插入”操作的回调,并且可以使用协程将其传递回viewmodel?

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

1 个答案:

答案 0 :(得分:0)

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

如果将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()   
}