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

Pere Casafont

07/08/2019, 11:25 AM
When I add the
suspend
modifier to a function that I know it will take long to compute, intellij bugs me with the
Redundant 'suspend' modifier
inspection. Am I doing something wrong? All I want is to force this function to be called from a coroutine scope...
g

gildor

07/08/2019, 11:36 AM
Yes,
suspend
doesn’t mean that it would somehow make blocking code non-blocking, but you can use
withContext(<http://Dispatchers.IO/Defatult|Dispatchers.IO/Defatult>) { someBlockingCode }
to move work out of current thread to some IO/Computation dispatcher
Do you have an example of such code?
p

Pere Casafont

07/08/2019, 12:26 PM
So let's imagine I have
Copy code
fun calculateExpensiveHash() {
  // computations taking 500-1500ms
}
I just want to enforce it being called from a coroutine scope, and to do so I'd add the
suspend
modifier...
e

Eric Martori

07/08/2019, 12:34 PM
if your function is not suspending or calling other suspending function it doesn't make sense to mark it as a suspend function. You can use
withContext
which will suspend the calling funtion untill your computation completes:
Copy code
suspend fun foo() = withContext(<http://Dispatchers.IO|Dispatchers.IO>){
    //expensive computation IO computation that returns 1
    1
}
p

Pere Casafont

07/08/2019, 12:37 PM
alright, thank you
g

gildor

07/08/2019, 12:50 PM
If it's a computation (so CPU bound task, not a some IO operation), so probably better to use Dispatchers.Default which CPU-bound dispatcher)
👍 4
p

Pere Casafont

07/08/2019, 12:53 PM
right, I had gotten it 🙂
b

bdawg.io

07/08/2019, 3:45 PM
Also, if you just want to force a CoroutineScope (for some reason?) you can also make it an extension function
fun CoroutineScope.calculateExpensiveHash() = ...
👍 2
p

Pere Casafont

07/08/2019, 4:15 PM
thanks
53 Views