Val Okafor
Val Okafor

Reputation: 3437

Unable to get my First Kotlin Coroutine Function to Work

I am struggling to get my first Coroutine function to work! I have a blocking function called GetContacts, which fetches device contacts. And I want to update a Livedata with the result of this query. This query works fine on its own, but I can't seem to get it to work inside Coroutine.

Here is my code

   val contactsList: MutableLiveData<List<ContactModel>> = MutableLiveData()

    fun getContactList(){
        viewModelScope.launch() {
            var contacts: List<ContactModel>? = null
            withContext(Dispatchers.IO){
                contacts = getListOfContactsOnDeviceAsync()
            }
            contactsList.value = contacts
        }
    }

    private fun getListOfContactsOnDeviceAsync(): List<ContactModel> =  GetContactHelper.getContacts()

I am getting error "Module with the Main dispatcher is missing. Add dependency providing the Main dispatcher, e.g. 'kotlinx-coroutines-android'" when I clearly have Android Coroutine dependency added.

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2'}

What am I missing? Any help appreciated!

Upvotes: 0

Views: 210

Answers (1)

Abed
Abed

Reputation: 5157

It looks like it's an issue in Kotlin Coroutines library 1.3.2 take a look at this issue, so as a solution, try to downgrade your android coroutine library to version 1.3.0 as @ispbox said in this comment.

Upvotes: 1

Related Questions