简体   繁体   English

协程 GlobalScope 延迟触发

[英]Coroutine GlobalScope triggered with delay

I want to show progress dialog if process time is more than 250ms.如果处理时间超过 250 毫秒,我想显示进度对话框。

I am trying to do it with Coroutines.我正在尝试使用协程来做到这一点。 My problem is whether or not I remove "delay(250)" line, it always runs dismissProgressDialog() first then it runs showProgressDialog().我的问题是我是否删除“delay(250)”行,它总是先运行dismissProgressDialog(),然后运行showProgressDialog()。 I think it is about GlobalScope.launch(Dispatchers.Main) because when I remove this, it runs showProgressDialog() first as expected.我认为这是关于 GlobalScope.launch(Dispatchers.Main) 因为当我删除它时,它会按预期首先运行 showProgressDialog() 。

fun showProgressDialog() =
    GlobalScope.launch(Dispatchers.Main) {
        if (!customDialog.isShowing) {
            forceCloseLoading = false

            LogUtils.e("progress show before delay")
            delay(250)
            LogUtils.e("progress show after delay")

            if (!forceCloseLoading) {
                customDialog.show()
            }
        }
    }

fun dismissProgressDialog() {
    forceCloseLoading = true
    LogUtils.e("progress dismiss")

    try {
        if (customDialog.isShowing) {
            customDialog.dismiss()
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }

}

Here is my logcat output:这是我的 logcat 输出:

progress dismiss
progress show before delay
progress show after delay

How can I show progress dialog only if process time is more than 250ms?仅当处理时间超过 250 毫秒时,如何才能显示进度对话框?

The code below will show a button, that when pressed will trigger a dialog if the work takes longer than 250ms.下面的代码将显示一个按钮,如果工作时间超过 250 毫秒,按下该按钮将触发一个对话框。 Upon competion a snackbar is shown to signal the work is done to the user.在比赛中,会显示一个小吃店,向用户发出工作已完成的信号。 If I understood you correctly this should demonstrate the functionality you asked for.如果我理解正确,这应该展示您要求的功能。

class MainActivity : AppCompatActivity() {
    // Create a scope for out coroutines to run on, with the coroutine context Unconfined.
    private val scope: CoroutineScope = CoroutineScope(Dispatchers.Unconfined)

    private lateinit var customDialogBuilder: AlertDialog.Builder
    private lateinit var customDialog: AlertDialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Create a dialog to display when task is in progress
        customDialogBuilder = AlertDialog.Builder(this)
            .setMessage("Working on it...")
            .setTitle("Loading...")

        // Set the listener where a coroutine job is launched. The job starts another job which will
        // take somewhere between 1..800 ms to complete. The parent job waits 250ms then checks if
        // the child job is completed, if not it displays the dialog.
        btn_process.setOnClickListener {
            scope.launch {

                // Launch a job with the work we are waiting on.
                val job = launchWork()
                delay(250)

                // Check if the job is still active, if so show the dialog.
                if (job.isActive) {
                    runOnUiThread {
                        customDialog = customDialogBuilder.show()
                    }
                }
            }
        }
    }

    private fun launchWork(): Job {
        return scope.launch {
            // Simulate some work.
            val workTime = Random.nextLong(1, 800)
            delay(workTime)

            runOnUiThread {
                // Dismiss dialog when done.
                if (customDialog.isShowing) {
                    customDialog.dismiss()
                }
                // Show some feedback that the work is done.
                Snackbar
                    .make(layout_root, "Work finished in ${workTime}ms", Snackbar.LENGTH_LONG)
                    .show()
            }
        }
    }
}

Layout, activity_main.xml:布局,activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:id="@+id/layout_root"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_process"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Process" />

</LinearLayout>

build.gradle (app): build.gradle(应用程序):

dependencies {

    ...

    def coroutines_version = "1.3.1"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"

    implementation 'com.google.android.material:material:1.0.0' // For snackbar

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM