Skip to content

Instantly share code, notes, and snippets.

@emitchel
Last active April 4, 2019 14:36
Show Gist options
  • Save emitchel/fe0e91bba853081c23a2be6497af030c to your computer and use it in GitHub Desktop.
Save emitchel/fe0e91bba853081c23a2be6497af030c to your computer and use it in GitHub Desktop.
// Somewhere on the UI thread
class MyActivity : Activity {
val eventBus: EventBus
//...
fun getData() {
showProgress()
eventBus.post(FetchArtistEventsEvent(artist))
}
@Subscribe(threadMode=ThreadMode.MAIN)
fun onEvent(event: RetrieveArtistEventsEvent){
hideProgress()
showEvents(event.artistEvents)
}
}
class ArtistRepository {
val eventBus: EventBus
//...
@Subscribe(threadMode=ThreadMode.BACKGROUND)
fun onEvent(event: FetchArtistEventsEvent) {
// Check if data has been stored over an hour ago from now
if (RepositoryUtil.isCacheStale(sharedPreferences, "ArtistEvent", event.artist.name, TimeUnit.HOURS.toSeconds(1))) {
// Reset the cache time to "now"
RepositoryUtil.resetCache(sharedPreferences, "ArtistEvent", event.artist.name)
// Call webservice synchronously
val freshEvents = api.findArtistEvents(event.artist.name).execute().body()
// Update/Insert events in database
bandsInTownDatabase.artistEventDao().upsert(freshEvents)
}
eventBus.post(RetrieveArtistEventsEvent(database.artistEventDao().getEventsByArtistId(event.artist.id)))
}
class FetchArtistEventsEvent(val artist: Artist)
class RetrieveArtistEventsEvent(val artistEvents: List<ArtistEvent>?)
}
// Retrofit web service interface
interface BandsInTownApi {
@GET("/artists/{artistName}/events")
fun findArtistEvents(
@Path("artistName") artistName: String
): Call<List<ArtistEventResponse>>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment