kotlin - 在kotlin中完成异步功能后如何执行另一个功能?
问题描述
我正在实例化以下变量:
phoneViewModel = ViewModelProvider(this).get(PhoneViewModel::class.java).also {it.initialRead()}
initialRead() 调用另一个异步检索数据的函数。当我在应用程序中使用 phoneViewModel 变量时,应用程序崩溃,因为 initialRead() 尚未完成。在“异步”实例化完成后,如何执行另一个函数,例如 usePhoneViewModel()?
public fun initialRead(onError: ((errorMessage: String) -> Unit)? = null) {
if (!isDownloadError) {
repository.initialRead(
Action0 { isDownloadError = false},
Action1 { error ->
isDownloadError = true
onError?.let {
val resources = getApplication<Application>().resources
onError.invoke(resources.getString(R.string.read_failed_detail))
}
}
)
}
}
并在 repo 中进行 initialRead
fun initialRead(successHandler: Action0?, failureHandler: Action1<RuntimeException>) {
relatedEntities.clear()
if (initialReadDone && entities.size > 0) {
observableEntities.setValue(entities)
return
}
var dataQuery = DataQuery().from(entitySet)
if (orderByProperty != null) {
dataQuery = dataQuery.orderBy(orderByProperty, SortOrder.ASCENDING)
}
zGW_EXT_SHIP_APP_SRV_Entities.executeQueryAsync(dataQuery,
Action1 { queryResult ->
val entitiesRead = convert(queryResult.entityList)
entities.clear()
entities.addAll(entitiesRead)
initialReadDone = true
observableEntities.value = entitiesRead
successHandler?.call()
},
failureHandler,
httpHeaders)
}
解决方案
鉴于此功能,我认为您不能。为您添加一个onSuccess
参数initialRead
,例如:
public fun initialRead(onSuccess: (() -> Unit)? = null, onError: ((errorMessage: String) -> Unit)? = null) {
if (!isDownloadError) {
repository.initialRead(
Action0 {
isDownloadError = false
onSuccess?.invoke()
},
Action1 { error ->
isDownloadError = true
onError?.let {
val resources = getApplication<Application>().resources
onError.invoke(resources.getString(R.string.read_failed_detail))
}
}
)
}
}
然后传递你想在那里做的事情:
ViewModelProvider(this).get(PhoneViewModel::class.java).also {
it.initialRead(onSuccess = { usePhoneViewModel() })
}
推荐阅读
- python - Python:从 800 万行文件中读取并存储到单独文件中的程序的效率
- algorithm - 算法。将两个 n 位二进制数相加。这个问题的循环不变量是什么?
- java - Spring认证过程失败
- python - Python 程序 - 将人的体重从磅转换为公斤 - 1
- javascript - 如何模拟具有属性的对象作为文件路径以获取 Karma jasmine 中的信息
- javascript - 你如何从谷歌表格发送 Skype 消息?
- liquibase - SQL 格式的变更集的失败消息
- javascript - Axios 在发布时将嵌套的 JSON 数组变为空
- python - 在ubuntu中重命名用户名后conda坏了
- java - 按下按钮后 JFrame 冻结