简体   繁体   English

在Kotlin中穿线的正确方法

[英]Proper way to thread in kotlin

I have thread code block which basically displays progress bar for 2 seconds then shows a recycler view. 我有线程代码块,它基本上显示进度条2秒钟,然后显示回收者视图。 I wonder if there is more proper way to write this for example coroutines or rxjava. 我想知道是否有更适当的方式编写此代码,例如协程或rxjava。 I tried coroutines but I got crashes. 我尝试了协程,但崩溃了。 Code : 代码:

 runOnUiThread {
            fabClose()
            isOpen = false
            rec_view.adapter=null
            progressBar.visibility = View.VISIBLE

        }
        val handler = Handler()
        val t = Timer()
        t.schedule(object: TimerTask() {
            override fun run() {
                handler.post {
                        runOnUiThread {
                            imageRecognition()
                            progressBar.visibility = View.GONE

                        }
                }
            }
        }, 2000)

While you could use coroutines, what you are trying to achieve seems pretty straightforward, it is only that you code looks a little bit more convoluted than necessary. 虽然可以使用协程,但是您要实现的目标似乎很简单,只是您的代码看起来比所需的要复杂得多。

You could try using the postDelayed() method of a Handler invoked on the main looper (which is the looper that lives in the main thread): 您可以尝试使用在postDelayed()位于主线程中的postDelayed()调用的HandlerpostDelayed()方法:

// Code to show the loader here
Handler(Looper.getMainLooper()).postDelayed({
    // Code to show the recyclerview here 
}, 2000)

Yes, You can try your code snippet with Kotlin Coroutines like following: 是的,您可以使用Kotlin Coroutines尝试使用以下代码段:

GlobalScope.launch(Dispatchers.Main) { // We launch new coroutine with Main thread as dispatcher
    fabClose()
    isOpen = false
    rec_view.adapter=null
    progressBar.visibility = View.VISIBLE
    // Here delay is suspended function which stops further execution of thread without blocking it.
    delay(2000L) // We provide non-blocking delay for 2 second which suspends this coroutine execution
    imageRecognition()
    progressBar.visibility = View.GONE
}

Here, GlobalScope is used to create our lauch Coroutine with Main Thread CoroutineContext (One can also use async too, difference between both is return type they provide) & we put our asynchronous code in sequential manner where Coroutine handles it's execution asynchronously. 在这里,GlobalScope用于创建我们的lauch主线程 CoroutineContext协程(你也可以使用async过,在两者之间的区别是,他们提供的返回类型),我们把我们的异步代码以顺序方式,其中协程处理它的执行异步。

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

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