Skip to content

Instantly share code, notes, and snippets.

@vferreirati
Last active October 18, 2018 13:31
Show Gist options
  • Save vferreirati/ab864f2db56bc3f5e8517d11ff299dcc to your computer and use it in GitHub Desktop.
Save vferreirati/ab864f2db56bc3f5e8517d11ff299dcc to your computer and use it in GitHub Desktop.
Basic entity repository using coroutines instead of AsyncTasks
package com.vferreirati.cervejeiros.repository
import androidx.lifecycle.MutableLiveData
import com.vferreirati.cervejeiros.data.dao.BeerDao
import com.vferreirati.cervejeiros.data.model.Beer
import com.vferreirati.cervejeiros.services.PunkService
import com.vferreirati.cervejeiros.services.model.BeerResponse
import kotlinx.coroutines.experimental.Dispatchers
import kotlinx.coroutines.experimental.GlobalScope
import kotlinx.coroutines.experimental.launch
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class BeerRepository @Inject constructor(private val beerDao: BeerDao,
private val punkService: PunkService) {
fun getBeers(): MutableLiveData<List<BeerResponse>> {
val beerList = MutableLiveData<List<BeerResponse>>()
GlobalScope.launch(Dispatchers.IO) {
val response = punkService.getBeers().execute()
if(response.isSuccessful) {
val beers = response.body()
beerList.postValue(beers)
}
}
return beerList
}
fun getBeerById(beerId: Int): MutableLiveData<BeerResponse> {
val beer = MutableLiveData<BeerResponse>()
GlobalScope.launch(Dispatchers.IO) {
val response = punkService.getBeerById(beerId).execute()
if(response.isSuccessful && !response.body()!!.isEmpty()) {
val beerResponse = response.body()!![0]
beer.postValue(beerResponse)
}
}
return beer
}
fun insertBeers(beers: List<Beer>) {
GlobalScope.launch(Dispatchers.IO) {
beerDao.insertList(beers)
}
}
fun update(beer: Beer) {
GlobalScope.launch(Dispatchers.IO) {
beerDao.update(beer)
}
}
fun delete(beerId: Int) {
GlobalScope.launch(Dispatchers.IO) {
beerDao.deleteById(beerId)
}
}
fun deleteAll() {
GlobalScope.launch(Dispatchers.IO) {
beerDao.deleteAll()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment