如何 return 从异步协程范围(例如 ViewModelScope)到您的 UI 的值?

How to return value from async coroutine scope such as ViewModelScope to your UI?

我正在尝试从数据库中检索单个条目,并在 viewModelScope 的帮助下成功地将值取回我的视图模型,但我希望此值为 return返回到位于片段中的调用函数,以便它可以显示在 TextView 上。我尝试 return 传统方式的价值,但它没有用。那么,我如何 return 这个值从 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
}

LiveData 可用于获取从 ViewModelFragment 的值。

创建函数 findbyID return 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

findbyId.observer(viewLifeCycleOwner, Observer { returnedrepo ->
   /* logic to set the textview */
})

感谢 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())
    }
}