Skip to content
This repository has been archived by the owner on Aug 2, 2024. It is now read-only.

Commit

Permalink
PR adjust to improve coroutines impl.
Browse files Browse the repository at this point in the history
  • Loading branch information
XinyueZ committed Nov 28, 2018
1 parent d76e7bd commit 076f51c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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) =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.
Expand All @@ -75,7 +75,9 @@ class PlantDetailViewModel(
plant = plantRepository.getPlant(plantId)
}

fun addPlantToGarden() = viewModelScope.launch {
gardenPlantingRepository.createGardenPlanting(plantId)
fun addPlantToGarden() {
viewModelScope.launch {
gardenPlantingRepository.createGardenPlanting(plantId)
}
}
}

0 comments on commit 076f51c

Please sign in to comment.