Skip to content

Instantly share code, notes, and snippets.

@digitalbuddha digitalbuddha/RoomStore.kt
Last active May 24, 2018

Embed
What would you like to do?
Store with Room
@Entity
data class User(
@PrimaryKey(autoGenerate = true) var uid: Int = 0,
val name: String,
val lastName: String)
@Dao
interface UserDao {
@Query("SELECT name FROM user")
fun loadAll(): Flowable<List<String>>
@Insert
fun insertAll(vararg users: User)
@Delete
fun delete(user: User)
}
@Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
val db = Room.databaseBuilder(SampleApp.appContext, AppDatabase::class.java, "db").build()
//store
class SampleRoomStore(fetcher: Fetcher<User, String>,
persister: RoomPersister<User, List<String>, String>,
stalePolicy: StalePolicy = StalePolicy.UNSPECIFIED) :
RoomInternalStore<User, List<String>, String>(fetcher, persister, stalePolicy)
val persister = object : RoomPersister<User, List<String>, String> {
override fun read(key: String): Observable<List<String>> {
return db.userDao().loadAll().toObservable().map { if (it.isEmpty()) throw Exception() else it }
}
override fun write(key: String, user: User) {
db.userDao().insertAll(user)
}
}
val fetcher=Fetcher<User,String> { Single.just(User(name = "Mike", lastName = "naki")) }
val store = SampleRoomStore( fetcher, persister)
//Usage
var foo = store.get("")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ strings1 -> val success = strings1 != null }) { throwable -> throwable.stackTrace }
foo = Observable.timer(15, TimeUnit.SECONDS)
.subscribe { it -> again() }
}
private fun again() {
val bar = store.fetch("")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ strings1 -> val success = strings1 != null }) { throwable -> throwable.stackTrace }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.