Skip to content Skip to sidebar Skip to footer

Proper Way To Thread In Kotlin

I have thread code block which basically displays progress bar for 2 seconds then shows a recycler view. I wonder if there is more proper way to write this for example coroutines o

Solution 1:

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

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

Solution 2:

Yes, You can try your code snippet with Kotlin Coroutines like following:

GlobalScope.launch(Dispatchers.Main) { // We launch new coroutine with Main thread as dispatcherfabClose()
    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 executionimageRecognition()
    progressBar.visibility = View.GONE
}

Here, GlobalScope is used to create our lauch Coroutine with Main ThreadCoroutineContext(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.

Post a Comment for "Proper Way To Thread In Kotlin"