Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'return' is not allowed here: Kotlin Coroutine launch(UI) block

fun onYesClicked(view: View) {

    launch(UI) {
        val res = post(context!!,"deleteRepo")

        if(res!=null){
            fetchCatalog(context!!)
            catalogActivityCatalog?.refresh()
        }
    }
}

Above code is working fine. I want to avoid the nested part in the if by returning (thereby stopping execution) if res == null, like this,

fun onYesClicked(view: View) {

    launch(UI) {
        val res = post(context!!,"deleteRepo")

        if(res==null)return                  //this line changed <---A

        fetchCatalog(context!!)              //moved outside if block
        catalogActivityCatalog?.refresh()    //moved outside if block
    }
}

It says 'return' is not allowed here when I use return in the line indicated by <--A

Is there a keyword to exit launch block in here? What is the alternative that can be used here instead of return?

like image 671
SadeepDarshana Avatar asked Jul 17 '18 05:07

SadeepDarshana


People also ask

How to start the coroutines in Kotlin?

There are mainly two functions in Kotlin to start the coroutines . The launch will not block the main thread, but on the other hand, the execution of the rest part of the code will not wait for the launch result since launch is not a suspend call. Following is a Kotlin Program Using Launch:

What is the use of delay in Kotlin coroutine?

Kotlin Coroutines on Android Suspend Function In Kotlin Coroutines As it is known that when the user calls the delay () function in any coroutine, it will not block the thread in which it is running, while the delay () function is called one can do some other operations like updating UI and many more things.

What is the difference between delay () and suspend () in Kotlin?

Suspend Function In Kotlin Coroutines As it is known that when the user calls the delay () function in any coroutine, it will not block the thread in which it is running, while the delay () function is called one can do some other operations like updating UI and many more things.

Is it possible to do try/ catch/finally in Kotlin?

Yes. The goal is have more concise and more composable way to do try/catch/finally so that, for example, you can encapsulate error handling logic specific to your application as a flow operator and reuse it everywhere in a declarative way. Generally, using "bare" try/catch/finally in Kotlin is not very idiomatic.


1 Answers

The destination of the return has to be specified using return@...

fun onYesClicked(view: View) {

    launch(UI) {
        val res = post(context!!,"deleteRepo")

        if(res==null)return@launch     //return at launch

        fetchCatalog(context!!)              
        catalogActivityCatalog?.refresh()    
    }
}
like image 191
Alexander Egger Avatar answered Sep 25 '22 05:09

Alexander Egger