首页 > 解决方案 > 在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)
}

标签: kotlinasynchronous

解决方案


鉴于此功能,我认为您不能。为您添加一个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() })
}

推荐阅读