Kotlin Coroutines with returning value

前端 未结 6 872
盖世英雄少女心
盖世英雄少女心 2020-12-17 08:54

I want to create a coroutine method which has returning value.

For example)

fun funA() = async(CommonPool) {
    return 1
}

fun funB() = async(Commo         


        
6条回答
  •  心在旅途
    2020-12-17 09:22

    Here is the way I did it, to return a Boolean value when trying to delete a phone number from my Room database. You can use the same pattern for what you are trying to accomplish. In my view model:

    private var parentJob = Job()
    private val coroutineContext: CoroutineContext get() = parentJob + Dispatchers.Main
    private val scope = CoroutineScope(coroutineContext)
    
    suspend fun removePhoneNumber(emailSets: EmailSets, personDetails: PersonDetails) : Boolean  {
        var successReturn = false
        scope.async(Dispatchers.IO) {
            val success = async {removePhoneNumbersAsync(emailSets,personDetails)}
            successReturn = success.await()
    
        }
        return successReturn
    }
    
    fun removePhoneNumbersAsync(emailSets: EmailSets, personDetails : PersonDetails):Boolean {
        var success = false
        try {
            val emailAddressContact = EmailAddressContact(emailSets.databaseId, personDetails.id, personDetails.active)
            repository.deleteEmailAddressContact(emailAddressContact)
            val contact = Contact(personDetails.id, personDetails.personName, personDetails.personPhoneNumber, 0)  
            repository.deleteContact(contact)
            success = true
        } catch (exception: Exception) {
            Timber.e(exception)
        }
        return success
    }
    

    In my Activity:

    runBlocking {
        if (v.tag != null) {
                val personDetails = v.tag as PersonDetails
                val success  = viewModel.removePhoneNumber(emailSets,personDetails)
                if (success) {
                    val parentView = v.parent as View
                    (parentView as? TableRow)?.visibility = View.GONE
                    val parentViewTable = parentView.parent as ViewGroup
                    (parentViewTable as? TableLayout)
                    parentViewTable.removeView(parentView)
                }
         }
    
    }
    

提交回复
热议问题