diff --git a/app/src/main/java/com/google/samples/apps/sunflower/data/GardenPlantingRepository.kt b/app/src/main/java/com/google/samples/apps/sunflower/data/GardenPlantingRepository.kt index 7eecbd538..e6cbdae6d 100644 --- a/app/src/main/java/com/google/samples/apps/sunflower/data/GardenPlantingRepository.kt +++ b/app/src/main/java/com/google/samples/apps/sunflower/data/GardenPlantingRepository.kt @@ -16,17 +16,24 @@ package com.google.samples.apps.sunflower.data +import kotlinx.coroutines.Dispatchers.IO +import kotlinx.coroutines.withContext + class GardenPlantingRepository private constructor( private val gardenPlantingDao: GardenPlantingDao ) { - fun createGardenPlanting(plantId: String) { - val gardenPlanting = GardenPlanting(plantId) - gardenPlantingDao.insertGardenPlanting(gardenPlanting) + suspend fun createGardenPlanting(plantId: String) { + withContext(IO) { + val gardenPlanting = GardenPlanting(plantId) + gardenPlantingDao.insertGardenPlanting(gardenPlanting) + } } - fun removeGardenPlanting(gardenPlanting: GardenPlanting) { - gardenPlantingDao.deleteGardenPlanting(gardenPlanting) + suspend fun removeGardenPlanting(gardenPlanting: GardenPlanting) { + withContext(IO) { + gardenPlantingDao.deleteGardenPlanting(gardenPlanting) + } } fun getGardenPlantingForPlant(plantId: String) = diff --git a/app/src/main/java/com/google/samples/apps/sunflower/viewmodels/PlantDetailViewModel.kt b/app/src/main/java/com/google/samples/apps/sunflower/viewmodels/PlantDetailViewModel.kt index f8d0caa4c..51b1a1f53 100644 --- a/app/src/main/java/com/google/samples/apps/sunflower/viewmodels/PlantDetailViewModel.kt +++ b/app/src/main/java/com/google/samples/apps/sunflower/viewmodels/PlantDetailViewModel.kt @@ -24,7 +24,7 @@ import com.google.samples.apps.sunflower.data.GardenPlantingRepository import com.google.samples.apps.sunflower.data.Plant import com.google.samples.apps.sunflower.data.PlantRepository import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers.IO +import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.Job import kotlinx.coroutines.launch @@ -53,7 +53,7 @@ class PlantDetailViewModel( * Since we pass [viewModelJob], you can cancel all coroutines launched by [viewModelScope] by calling * viewModelJob.cancel(). This is called in [onCleared]. */ - private val viewModelScope = CoroutineScope(IO + viewModelJob) + private val viewModelScope = CoroutineScope(Main + viewModelJob) /** * Cancel all coroutines when the ViewModel is cleared. @@ -75,7 +75,9 @@ class PlantDetailViewModel( plant = plantRepository.getPlant(plantId) } - fun addPlantToGarden() = viewModelScope.launch { - gardenPlantingRepository.createGardenPlanting(plantId) + fun addPlantToGarden() { + viewModelScope.launch { + gardenPlantingRepository.createGardenPlanting(plantId) + } } }