Skip to content

Instantly share code, notes, and snippets.

@Lzyct
Last active March 18, 2019 15:11
Show Gist options
  • Select an option

  • Save Lzyct/ad5ff05f6e294a2e1983a9b4a95c0ad7 to your computer and use it in GitHub Desktop.

Select an option

Save Lzyct/ad5ff05f6e294a2e1983a9b4a95c0ad7 to your computer and use it in GitHub Desktop.
Sample Room DB with Rx
class RepoTest(private val testDao:TestDao){ //inject dao using Koin
fun insertTest(test:Test) : Single<Resource<String>> = testDao.insertTest(test)
. .subscribeOn(Schedulers.io())
.map<Resource<String>> { t -> Resource.Success(t.toString()) } // convert primary key value to String
.onErrorReturn { Resource.Failure(it) }
.observeOn(AndroidSchedulers.mainThread())
}
sealed class Resource<out T> {
data class Success<out T>(val data: T?) : Resource<T>()
data class Failure<out T>(val throwable: Throwable) : Resource<T>()
}
@Dao
interface TestDao{
@Insert(onConflict = OnConflictStrategy.REPLACE) // replace data on conflict
fun insertTest(test: Test): Single<Long> // return primary key
}
class TestViewModel(private val repo:RepoTest) { // inject repo using Koin
fun insertTest(test:Test){
repo.insertTest(test).subscribe(
{
when (it) {
is Resource.Success -> {
e { "success save data with primary key : ${it.data}" }
}
is Resource.Failure -> {
e (it.throwable)
}
else -> throw IllegalStateException("State not known or implemented.")
}
}, {
it.printStackTrace()
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment