在Kotlin中完成异步功能后,如何执行另一个功能?

时间:2020-10-21 09:16:58

标签: kotlin asynchronous

我正在实例化以下变量:

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))
                }
            }
        )
    }
}

和在仓库中的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)
}

1 个答案:

答案 0 :(得分:0)

鉴于此功能,我认为您无法做到。在您的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() })
}