Skip to content

Instantly share code, notes, and snippets.

@emitchel
Last active April 4, 2019 14:36
Show Gist options
  • Save emitchel/634b7ce0a8aef8245f337f27b6e1db48 to your computer and use it in GitHub Desktop.
Save emitchel/634b7ce0a8aef8245f337f27b6e1db48 to your computer and use it in GitHub Desktop.
// Somewhere on the UI thread
class MyActivity : Activity {
val repo: ArtistRepository
//...
fun getData() {
showProgress()
disposable = repo.fetchEvents(artist)
.subscribe {
hideProgress
showData(it)
}
}
override fun onDestroy() {
super.onDestroy()
disposable.dispose()
}
}
class ArtistRepository {
//...
fun fetchEvents(artist: Artist) : Observable {
// Image the same RepositoryUtil in rx style
return RepositoryUtil.isCacheStaleObservable(sharedPreferences, "ArtistEvent", artist.name, TimeUnit.HOURS.toSeconds(1))
.flatMap { isStale ->
// Check if data has been stored over an hour ago from now
if (isStale) {
// Reset the cache time to "now"
RepositoryUtil.resetCache(sharedPreferences, "ArtistEvent", artist.name)
// Call webservice synchronously
val freshEvents = api.findArtistEvents(artist.name).execute().body()
// Update/Insert events in database
bandsInTownDatabase.artistEventDao().upsert(freshEvents)
}
return database.artistEventDao().getEventsByArtistId(artist.id)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
}
// Retrofit web service interface
interface BandsInTownApi {
@GET("/artists/{artistName}/events")
fun findArtistEvents(
@Path("artistName") artistName: String
): Observable<List<ArtistEventResponse>>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment