https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

Andrey B.

03/17/2021, 4:16 PM
Hello everyone.... Am I going crazy? In my Android ViewModel I have something like this:
Copy code
viewModelScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) { someFunction() }
....
fun someFunction(){}
It's compiling!!! But whyyyy? Shouldn't someFunction() be suspendable??
z

Zach Klippenstein (he/him) [MOD]

03/17/2021, 4:17 PM
You can call regular, non-suspending functions from suspending functions. You just can’t call suspending functions from regular ones.
a

Andrey B.

03/17/2021, 4:18 PM
Well .... is it something new? I'm sorry for the stupid question
a

albertosh

03/17/2021, 4:18 PM
The only limitation is that you must invoke suspended functions in a suspended block If you could only invoke suspend methods in a suspended block you would not be able to do even a simple
val i = 0
as it’s synchronous
I’d say that is a consistent behaviour from the introduction of
suspend
z

Zach Klippenstein (he/him) [MOD]

03/17/2021, 4:19 PM
Nope, that’s always been the case, and it’s very common to call non-suspending functions from suspending ones.
❤️ 1
☝️ 1
a

Andrey B.

03/17/2021, 4:20 PM
Okay guys, thank you so much for your help!
z

Zach Klippenstein (he/him) [MOD]

03/17/2021, 4:21 PM
I really like how this article explains it
👏 1
❤️ 1
a

Andrey B.

03/17/2021, 4:21 PM
I'd just freaking love this community! Thank you so much ❤️
I def gonna read the article
@Zach Klippenstein (he/him) [MOD] but will the non suspending function block the calling suspending one? 🤔
z

Zach Klippenstein (he/him) [MOD]

03/17/2021, 4:33 PM
Yes. However, because you’re launching your coroutine on the IO dispatcher, it will run on a background thread and it won’t block your app’s main thread.
a

Andrey B.

03/17/2021, 4:33 PM
Got it, thank you :)
g

gildor

03/18/2021, 1:26 AM
One more addition, even if you mark function with suspend modifier, it doesn't mean that it automatically non-blocking, it just means that it can call other suspend functions
e

Erik

03/18/2021, 3:22 PM
This is an excellent question, actually! Why would someone assume that non suspending functions should be callable from a coroutine context?
5 Views