这里是 Kotlin 的新手,正在尝试学习使用高阶函数和传递 lambda 的最佳方法。我创建了这个方法来调用 API 并返回从字符串创建的对象,或者如果出现问题则返回失败。
fun getDeviceStatus(onSuccess: (Device) -> Unit, onFailure: ((String) -> Unit)? = null) {
FuelClient.get(DEVICE_URL,
success = { responseString ->
val adapter = MoshiUtil.moshi.adapter(Device::class.java)
val deivce= adapter.fromJson(responseString)!!
onSuccess(device)
},
failure = { onFailure?.invoke(it.message!!)})
}
我可以像这样很好地使用这个函数:
DeviceService.getDeviceStatus(
{ w ->
print("device")
},
{ e -> print(e) })
但让我有点困扰的是,我看不到函数的名称以了解每个函数的作用。我想知道是否有更清洁/更好的方法来做到这一点,比如
DeviceService.getDeviceStatus(){
onSuccess{print("device")}
onFailure{print("error")}
}
或者也许
DeviceService.getDeviceStatus()
.onSuccess{print("device")}
.onFailure{print("error")}
但是那些给出了错误。关于如何最好地处理非常常见的 onSuccess/onFailure 用例有什么想法吗?谢谢
最佳答案
您可以为 kotlin 中的每个变量附加一个名称。像这样更改您的代码
DeviceService.getDeviceStatus(
onSuccess = { w ->
print("device")
},
onFailure = { e -> print(e) })
关于android - 在 Kotlin 中传递多个 lambda 函数以处理成功/失败的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50498769/