Hello, I’m getting the attached warning in a suspe...
# coroutines
a
Hello, I’m getting the attached warning in a suspend function inside an Android activity that implements the CoroutineScope. The code seems to work as expected but I’m a bit confused with the warning. Any ideas?
g
Could you show original code
a
I’m just trying to craft the example bellow
the warning is on the searchWikipedia function and the async call inside it
What I’m trying to achieve is to hide the async/await inside the suspend function to make the code easier/cleaner
g
you never should hide async or deferred
also, I don’t see any reason for this code to use async
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
will work the same way
this is valid warning in this case, because you launch coroutine from suspend function, so it cause ambigious context resolution (suspend function has call site context but this async actually uses CoroutineScope context which may be different)
a
Ok I changed the function to: private suspend fun searchWikipedia() = withContext(Dispatchers.IO) { wikipedia(searchInput.text.toString()) }
s
I think withContext with will still trigger ambigious coroutineContext, will it not?
a
Thank you @gildor
No it does not produce a warning
s
okay, quick question whats the full signature of wikipedia fn?
a
fun wikipedia(keyword: String): String
It’s a synchronous function no async staff inside it
s
ok thanks. @glidor if i understand withContext makes current coroutineContext + new dispatcher whilst async coroutineContext + new job(parentJob=coroutineContext[Job]) ? both deriving from same coroutineContext why is one ambigious?
g
think withContext with will still trigger ambigious coroutineContext, will it not
@sitepodmatt No, because no new coroutines are started, withContext doesn’t start new coroutines in scope, just a suspend function, so no ambigious context resolution, withContext always use context of suspend function
s
okay thanks, much to digest
g
also, this example may be changed to not allow you to use withContext, for example if you want to launch multiple coroutines in parallel
in this case you just should follow suggestion of this warning and use
coroutineScope
function that will create a new scope using suspend function context which allow you to run inside multiple child coroutines and
coroutineScope
function suspend untill all child coroutines do not finish work
for example:
Copy code
suspend fun searchWikipedia(): String {
    return coroutineScope {
        val result1 = async(<http://Dispatchers.IO|Dispatchers.IO>) { wikipedia(searchInput.text.toString()) }
        val result2 = async(<http://Dispatchers.IO|Dispatchers.IO>) { wikipedia(searchInput2.text.toString()) }
        result1.await() + result2.await()
    }
}
a
Thank you guys
👍 1