Created
November 6, 2017 23:35
-
-
Save jonathanrz/f6cc588aee9867c4a7b3fb5acf369a73 to your computer and use it in GitHub Desktop.
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
| interface DataSource { | |
| fun all(): Observable<List<Data>> | |
| fun save(data: Data): Boolean | |
| } | |
| class DataRepository(private val dao: DataDao) : DataSource { | |
| private val generateData: () -> List<Data> = { | |
| dao.all() | |
| } | |
| private val mergeData: (List<Data>, Data) -> List<Data> = { cache, newData -> | |
| val index = cache.indexOfFirst { it.id == newData.id } | |
| when(index) { | |
| -1 -> cache + newData | |
| 0 -> (arrayOf(newData) as List<Data>) + cache.subList(1, cache.size) | |
| else -> cache.subList(0, index - 1) + newData + cache.subList(index + 1, cache.size) | |
| } | |
| } | |
| private val dataObservable = DatabaseObservable<Data>(generateData, mergeData) | |
| override fun all(): Observable<List<Data>> = dataObservable.cache() | |
| override fun save(data: Data): Boolean { | |
| val id = dao.save(data) | |
| return if(id != 0L) { | |
| data.id = id | |
| dataObservable.newData(data) | |
| true | |
| } else { | |
| false | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment