首页 > 解决方案 > 如何在 Kotlin 中等待并继续执行

问题描述

基本上,我正在尝试在广告完成后立即继续执行。

目前,我正在使用delay这不是很方便。当延迟发生时,一些用户不会等待或简单地关闭活动。

我目前的做法:

override fun onRequestStarted() {
    showAd()
}

private fun Context.showAd(): Boolean {
    mInterstitialAd?.fullScreenContentCallback = object : FullScreenContentCallback() {

    /** Some other function **/

    override fun onAdShowedFullScreenContent() {
        isAdWatched = true
    }
}

override fun onRequestIntent() {
    GlobalScope.launch {
        delay(10000L)

        if (isAdWatched) {
            isAdWatched = false
            super.onRequestIntent(intent)
        }
    }
}

标签: androidkotlin

解决方案


您可以将基于回调的 API 转换为挂起函数。

创建一个在回调触发时返回的挂起函数。对于此示例,我假设您只想等待广告返回,无论它是否被观看。我尚未对此进行测试,但文档暗示此特定功能onAdDismissedFullScreenContent是您唯一需要响应才能知道广告何时完成(或从未加载)的功能。

/** Show the ad and suspend until it is dismissed. */
suspend fun InterstitialAd.showAndAwait(activity: Activity) = suspendCoroutine<Unit> { cont ->
    fullScreenContentCallback = object : FullScreenContentCallback() {
        override onAdDismissedFullScreenContent() {
            cont.resume(Unit)
        }
    }
    showAd(activity)
}

您将不得不更改您的设计,以便功能不会在您覆盖的这两个功能之间分开。我不知道你是如何调用这两个函数的,所以我不能确切地建议你需要改变什么。但最终,要执行您所描述的操作,您将调用一个启动协程的函数,并在协程中调用上述挂起函数来显示广告,然后执行您接下来想做的任何事情。像这样的东西:

fun foo() {
    lifecycleScope.launch {
        mInterstitialAd?.showAndAwait()
        doSomethingAfterReturnedFromAd()
    }
}

永远不要使用 GlobalScope。在最新版本的 Kotlin Coroutines 中,它会在您使用它时显示编译器警告,尽管它并没有完全弃用,因为在一些非常特殊的情况下它可能有有用的应用程序。你应该使用lifecycleScope这个。


推荐阅读