gpt4 book ai didi

android - 此 Kotlin 代码无法访问 Handler()postDelayed,如何解决?

转载 作者:行者123 更新时间:2023-11-29 19:12:01 27 4
gpt4 key购买 nike

我有一个函数,我只是想明确地延迟返回值

private fun loadData(): DataModel? {
Handler(Looper.getMainLooper()).postDelayed(
when (fetchStyle) {
FetchStyle.FETCH_SUCCESS -> return DataModel("Data Loaded")
FetchStyle.FETCH_EMPTY -> return DataModel("")
FetchStyle.FETCH_ERROR -> throw IllegalStateException("Error Fetching")
}, 3000)
}

然而,有一个警告状态,即 postDelayed 无法访问,因此不会触发 3s 延迟。

为了使其可访问,我必须在周围添加额外的括号

private fun loadData(): DataModel? {
Handler(Looper.getMainLooper()).postDelayed({
when (fetchStyle) {
FetchStyle.FETCH_SUCCESS -> DataModel("Data Loaded")
FetchStyle.FETCH_EMPTY -> DataModel("")
FetchStyle.FETCH_ERROR -> throw IllegalStateException("Error Fetching")
}}, 3000)
}

但是,我不能再返回 DataModel 值了。我怎样才能解决这个问题以延迟 3 秒,同时我仍然可以返回相应的 DataModel 或抛出异常?

最佳答案

如果只想阻塞当前线程,可以使用Thread.sleep:

private fun loadData(): DataModel? {
Thread.sleep(3000);
return when (fetchStyle) {
FetchStyle.FETCH_SUCCESS -> DataModel("Data Loaded")
FetchStyle.FETCH_EMPTY -> DataModel("")
FetchStyle.FETCH_ERROR -> throw IllegalStateException("Error Fetching")
}
}

使用 HandlerRunnable 的示例,带有单独的回调函数:

private fun loadData(): DataModel? {
Handler(Looper.getMainLooper()).postDelayed({
val result = when (fetchStyle) {
FetchStyle.FETCH_SUCCESS -> DataModel("Data Loaded")
FetchStyle.FETCH_EMPTY -> DataModel("")
FetchStyle.FETCH_ERROR -> throw IllegalStateException("Error Fetching")
}
loadDataCallback(result)
}, 3000)
}

fun useLoadData() {
loadData()
}

private fun loadDataCallback(dataModel: DataModel?) {
// use result here
}

一种更像 Kotlin 的方法,传递一个函数作为回调:

private fun loadData(callback: (DataModel?) -> Unit): DataModel? {
Handler(Looper.getMainLooper()).postDelayed({
val result = when (fetchStyle) {
FetchStyle.FETCH_SUCCESS -> DataModel("Data Loaded")
FetchStyle.FETCH_EMPTY -> DataModel("")
FetchStyle.FETCH_ERROR -> throw IllegalStateException("Error Fetching")
}
callback(result)
}, 3000)
}

fun useLoadData() {
loadData { dataModel ->
// use result here
}
}

请注意,这些示例不会阻塞任何线程,原始示例代码的 Handler(Looper.getMainLooper()) 部分(我为这些示例保留的)将执行when 语句以及之后返回主线程的回调。

关于android - 此 Kotlin 代码无法访问 Handler()postDelayed,如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44997227/

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