简体   繁体   中英

run coroutine with parent's ViewModel scope

I just getting started with coroutines and I'm not quite sure whether I'm on the right way using it. My android app has only 1 activity with several fragments and dialog fragments. I created a feature which asked user if he/she accepts to do something. The app shows a DialogFragment with Yes/No buttons. If user clicks Yes , it closes the dialog and does the job.

I would like to start the heavy job in activity's viewModelScope, so it will continue to execute at background event when user navigates to other fragments.

Parent's ViewModel:

class ActivityViewModel: ViewModel(){
    fun doJob(){
        viewModelScope.launch{
            //Do the heavy job
        }
    }
}

Dialog Fragment ViewModel:

class DialogViewModel: ViewModel(){
    var activityVM: ActivityViewModel
    fun onYesClicked(){
        activityVM.doJob()
    }
}

I guess the job is executed under DialogFragment's ViewModel scope instead of Activity's ViewModel scope. It leads to an issue that when the job runs slower than expected, it's canceled because the dialog is dismissed.

I'm not sure if this is common practice as I can't find any similar discussion. Please help to point me where am I wrong on this code or there is a best practice for this case.

I ended up with a custom coroutine scope on the activity viewModel. By doing this, I manually cancel the coroutines when activity closing event instead of dialog fragment dismissing.

class ActivityViewModel: ViewModel(){
    private val mainActivityScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    fun doJob(){
        mainActivityScope.launch{
            //Do the heavy job
        }
    }

    override fun onCleared() {
        super.onCleared()
        mainActivityScope.cancel()
    }

}

class DialogViewModel: ViewModel(){
    var activityVM: ActivityViewModel
    fun onYesClicked(){
        activityVM.doJob()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM