gpt4 book ai didi

android - Observe Kotlin 中的返回值

转载 作者:行者123 更新时间:2023-12-03 10:56:24 24 4
gpt4 key购买 nike

如何从观察者返回一个值?

    val clockInAndOutTime = ClockInAndOutTime()
clockInAndOutTime.id = 12
longToast("Name " +displayName(clockInAndOutTime.id.toString()))

private fun displayName(userId: String): String {

var name = ""
organizationViewModel.refreshList()
organizationViewModel.organization.observe(
this, Observer { resource ->
resource?.data.let {
it?.forEach { organization ->
if (organization.user_id == userId) {
name = organization.user_name!!
Log.d(TAG, "name is $name")
}else{
Log.d(TAG,"not found")
}
}
}
}
)
return name
}

在 displayName 函数中,我们可以得到名字,但是在 toast 中, Name总是显示为空。

最佳答案

你不能那样做。在你的 Observer 中调用一个函数

private fun displayName(userId: String, onNameFound: (String) -> Unit): String {

var name = ""
organizationViewModel.refreshList()
organizationViewModel.organization.observe(
this, Observer { resource ->
resource?.data.let {
it?.forEach { organization ->
if (organization.user_id == userId) {
name = organization.user_name!!
Log.d(TAG, "name is $name")
onNameFound(name)
}else{
Log.d(TAG,"not found")
}
}
}
}
)
return name
}

然后将其称为
displayName(clockInAndOutTime.id.toString()) { longToast("Name $it") }

关于android - Observe Kotlin 中的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57310829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com