This file contains 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 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