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

Tolriq

11/23/2018, 8:41 PM
If your function is marked suspend then you are calling it from a coroutineScope already. So it's maybe better to do
Copy code
suspend fun fetchCharacterData(): CharacterGenerator.CharacterData = {
            val apiData = withContext(<http://Dispatchers.IO|Dispatchers.IO>) { URL(CHARACTER_DATA_ENDPOINT).readText()} 
            CharacterGenerator.fromApiData(apiData)
        }
to start on good bases.
z

zak.taccardi

11/23/2018, 8:43 PM
CharacterGenerator.fromApiData(apiData)
should be called on the default dispatcher though
t

Tolriq

11/23/2018, 8:44 PM
Maybe my English is realy bad, but that's exactly what I'm trying to say actually 😉
m

Mike Palarz

11/23/2018, 8:48 PM
Ughhh, still having issues. I can't seem to get
fetchCharacterData()
written correctly. I've tried what @Tolriq recommended, but I'm getting a ton of compiler errors, namely that a suspension function can only be called within a coroutine context...
t

Tolriq

11/23/2018, 8:52 PM
Then you might want to read the coroutine starting guide to start.
m

Mike Palarz

11/23/2018, 8:55 PM
I will do that. Thank you for all of the help so far! 🙂
I actually think I got this to work! Here's how I've adjusted `fetchCharacterData()`:
Copy code
suspend fun fetchCharacterData(): CharacterGenerator.CharacterData = withContext(Dispatchers.Default){
    val apiData = withContext(<http://Dispatchers.IO|Dispatchers.IO>) { URL(CHARACTER_DATA_ENDPOINT).readText() }
    CharacterGenerator.fromApiData(apiData)
}
And then I call
fetchCharacterData()
as follows:
Copy code
generateButton.setOnClickListener {
            launch {
                characterData = fetchCharacterData()
                displayCharacterData()
            }
        }
Not sure if either of you have any comments on this, but I believe this is along the lines of what both of you were recommending. Thanks again!
2 Views