我正在尝试从数据库中检索单个条目,并借助viewModelScope成功地将其值返回到我的View模型中,但我希望将此值返回到驻留在其中的调用函数片段,以便可以将其显示在TextView上。我试图以常规方式返回该值,但是没有用。那么,如何将这个值从viewModelScope.launch返回到调用函数?
查看模型
fun findbyID(id: Int) {
viewModelScope.launch {
val returnedrepo = repo.delete(id)
Log.e(TAG,returnedrepo.toString())
// how to return value from here to Fragment
}
}
存储库
suspend fun findbyID(id : Int):userentity{
val returneddao = Dao.findbyID(id)
Log.e(TAG,returneddao.toString())
return returneddao
}
答案 0 :(得分:5)
requires (N == sizeof new unsigned short)
可用于从LiveData
到ViewModel
获取价值。
使函数Fragment
返回findbyID
并在片段中观察它。
LiveData
中的功能
ViewModel
fun findbyID(id: Int): LiveData</*your data type*/> {
val result = MutableLiveData</*your data type*/>()
viewModelScope.launch {
val returnedrepo = repo.delete(id)
result.postValue(returnedrepo)
}
return result.
}
中的观察者
Fragment
答案 1 :(得分:1)
感谢Nataraj KR的帮助!
以下是对我有用的代码。
查看模型
class ViewModel(application: Application):AndroidViewModel(application) {
val TAG = "ViewModel"
val repo: theRepository
val alldata:LiveData<List<userentity>>
val returnedVal = MutableLiveData<userentity>()
init {
val getDao = UserRoomDatabase.getDatabase(application).userDao()
repo = theRepository(getDao)
alldata = repo.allUsers
}
fun findbyID(id: Int){
viewModelScope.launch {
returnedVal.value = repo.findbyID(id)
}
}
}
片段
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val usermodel = ViewModelProvider(this).get(ViewModel::class.java)
usermodel.alldata.observe(this, Observer {
Log.e(TAG,usermodel.alldata.value.toString())
})
usermodel.returnedVal.observe(this, Observer {
tv1.text = usermodel.returnedVal.value.toString()
})
allData.setOnClickListener {
tv1.text = usermodel.alldata.value.toString()
}
findByID.setOnClickListener {
usermodel.findbyID(et2.text.toString().toInt())
}
}