Skip to content

Instantly share code, notes, and snippets.

@vferreirati
Last active October 18, 2018 18:12
Show Gist options
  • Save vferreirati/ad28a3ed921c5d1633249c3b4863edba to your computer and use it in GitHub Desktop.
Save vferreirati/ad28a3ed921c5d1633249c3b4863edba to your computer and use it in GitHub Desktop.
class BeerListViewModel (private val beerRepository: BeerRepository): ViewModel(), CoroutineScope {
private var job = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.IO + job
fun getBeers(): LiveData<List<BeerResponse>> {
val beers = MutableLiveData<List<BeerResponse>>()
launch {
beers.postValue(beerRepository.getBeers())
}
return beers
}
fun onDestroy() {
job.cancel()
}
}
class BeerRepository @Inject constructor(private val beerDao: BeerDao,
private val punkService: PunkService) {
suspend fun getBeers(): List<BeerResponse>? {
val response = punkService.getBeers().await()
return response.body()
}
suspend fun getBeerById(beerId: Int): BeerResponse? {
val response = punkService.getBeerById(beerId).await()
return response.body()?.get(0)
}
class DetailViewModel (private val beerRepository: BeerRepository): ViewModel(), CoroutineScope {
private var job = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.IO + job
fun getBeer(beerId: Int): LiveData<BeerResponse> {
val beer = MutableLiveData<BeerResponse>()
launch {
beer.postValue(beerRepository.getBeerById(beerId))
}
return beer
}
fun onDestroy() {
job.cancel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment