Programmer123
Programmer123

Reputation: 113

Cannot call suspend function from launch

Im new to kotlin coroutines and I'm trying to call a suspend function from oncreate using launch. But the code would not execute.

launch {
    callSomeApi()
}

suspend fun callSomeApi() {
    withContext(Dispatcher.IO) {
        //perform network call
    }
}

It says suspend function should only be called from a coroutine or other suspend function. Although Im calling it from launch. Please let me know what am I doing wrong? please see attached image

Upvotes: 1

Views: 1528

Answers (1)

CodeRanger
CodeRanger

Reputation: 370

You have to do like this :

  CoroutineScope(Dispatchers.Main).launch {
            someSuspendFunction()
        }

this way you assign a CoroutineScope to manage the coroutines processes. Keep in mind that you have to import coroutine dependencies completely:

    // coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.0'
implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'

Upvotes: 2

Related Questions