为什么我的进度条显示在内联协程函数之后,而不是之前?

问题描述 投票:0回答:1

当我使用 Fuel 从平板电脑向服务器发送 HTTP 请求时,我想在相关函数开始运行之前在屏幕上显示进度栏。但由于未知的原因,一旦函数完成其工作就会发生这种情况。

ProgressBar 是通过此函数以编程方式定义的:

protected fun initProgressBar(constraintLayoutID: Int): ProgressBar {
        val originalConstraintLayout = findViewById<ConstraintLayout>(constraintLayoutID)
        progressBar = ProgressBar(this).apply {
            id = getInteger(R.integer.INT_PROGRESS_BAR_ID)
            elevation = 999F
            isIndeterminate = true
            layoutParams = ViewGroup.LayoutParams(300, 300)
            visibility = View.GONE

            originalConstraintLayout.addView(this)
        }

        ConstraintSet().run {
            clone(originalConstraintLayout)

            for(position in listOf(ConstraintSet.TOP, ConstraintSet.START, ConstraintSet.END, ConstraintSet.BOTTOM))
                connect(progressBar!!.id, position, constraintLayoutID, position,0)
            applyTo(originalConstraintLayout)
        }
        return progressBar!!
    }

我尝试单独显示/隐藏进度栏,它工作得很好。这是内联函数,在发送主请求之前应该显示它:

inline fun <reified T : DefaultResponse> sendRequest(
        routeName: String = "",
        routeArgs: String = ""
    ): T = runBlocking { // Help : https://fuel.gitbook.io/documentation/support/fuel-coroutines
        owner.runOnUiThread {
            owner.showProgressBar() // Should display at this point, not after
        }

        val adaptedResponse = ResponseFactory.getInstance(owner).getResponseObjectFor(T::class.java.name, routeName)
        val (request, response, result) = Fuel.get(
            "%s%s?%s%s".format(
                networkManager.getURLConnection(),
                (adaptedResponse as DefaultResponse).getRouteName(),
                routeArgs,
                getIndustrialTrypticArgs()
            )
        ).awaitObjectResponseResult(adaptedResponse)

        val exception =
            FailedRequestException(owner.getString(R.string.STR_EXCEPTION_RM_FAILED_REQUEST)).apply {
                setHTTPMessage(response.responseMessage)
                setStatusCode(response.statusCode)
                setUsedRequest(request.url)
            }

        return@runBlocking result.fold<T>(
            { responseObject ->
                if (response.statusCode != 200)
                    throw exception
                return@fold responseObject as T
            },
            { error ->
                throw exception.setOriginalError(error.exception)
            }
        )
    }

另外,我还添加了对 runOnUiThread 的调用以进行显示,并在某个时刻使用“launch { ... }”封装在不同的协程线程中,但它不起作用(在执行结束后仍然出现内联函数)。

因为它是内联函数?或者担心并发线程?

kotlin coroutine android-progressbar inline-functions fuel
1个回答
0
投票

runOnUiThread
是异步的。由于您希望行为是同步,这意味着按照代码出现的顺序,您应该使用
withContext(Dispatchers.Main)
来代替。

withContext(Dispatchers.Main) {
    owner.showProgressBar()
}

withContext
是一个挂起函数,可以更改内部代码在哪个线程上同步运行。

© www.soinside.com 2019 - 2024. All rights reserved.