When I add the `suspend` modifier to a function th...
# coroutines
p
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
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
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
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
alright, thank you
g
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
right, I had gotten it 🙂
b
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
thanks
104 Views