Last active
March 18, 2019 15:11
-
-
Save Lzyct/ad5ff05f6e294a2e1983a9b4a95c0ad7 to your computer and use it in GitHub Desktop.
Sample Room DB with Rx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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()) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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>() | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @Dao | |
| interface TestDao{ | |
| @Insert(onConflict = OnConflictStrategy.REPLACE) // replace data on conflict | |
| fun insertTest(test: Test): Single<Long> // return primary key | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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