Skip to content

Instantly share code, notes, and snippets.

@pamartineza
Last active February 24, 2018 10:48
Embed
What would you like to do?
class FavoritesProvider : IFavoritesProvider {
val database = FirebaseDatabase.getInstance()
val gson = Gson()
val favoritesCache = FavoritesMemoryCache()
override fun saveBusStopFavoritesList(favorites: List<BusStopFavorite>) {
//save in cache
favoritesCache.saveBusStopFavoritesList(favorites)
//save in remote
val json = gson.toJson(favorites)
database.getReference(getBusStopFavoritesPath(getCurrentUid())).setValue(json)
}
override fun retrieveBusStopFavoritesListSingle(): Single<List<BusStopFavorite>> {
val cachedFavorites = favoritesCache.retrieveBusStopFavoritesList()
if (cachedFavorites != null) {
return Single.just(cachedFavorites)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
} else {
return Single.create<LinkedList<String>> { emitter ->
database.getReference(getBusStopFavoritesPath(getCurrentUid()))
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(error: DatabaseError) {
emitter.onError(error.toException())
}
override fun onDataChange(datasnapshot: DataSnapshot) {
val json = datasnapshot.value as String?
if (json != null) {
val listOfFavoritesType = object : TypeToken<List<BusStopFavorite>>() {}.type
val list = gson.fromJson<List<BusStopFavorite>>(json, listOfFavoritesType)
//save in cache
favoritesCache.saveBusStopFavoritesList(list)
emitter.onSuccess(list)
} else {
emitter.onSuccess(List())
}
}
})
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment