Skip to content

Instantly share code, notes, and snippets.

@emitchel
Last active April 4, 2019 14:36
Show Gist options
  • Save emitchel/49ed7672a14b8ddb8b0918965fe62e5b to your computer and use it in GitHub Desktop.
Save emitchel/49ed7672a14b8ddb8b0918965fe62e5b to your computer and use it in GitHub Desktop.
// Somewhere on the UI thread
class MyActivity : Activity {
//...
fun getData() {
showProgress()
GetArtistEvents(database, api, sharedPreferences).execute(artist)
}
}
class GetArtistEvents(val database: BandsInTownDatabase, val api: BandsInTownApi, val sharedPreferences: SharedPreferences) :
AsyncTask<Artist, Void, List<ArtistEvent>>() {
override fun doInBackground(vararg artist: Artist): List<ArtistEvent> {
// Check if data has been stored over an hour ago from now
if (RepositoryUtil.isCacheStale(sharedPreferences, "ArtistEvent", artist.first().name, TimeUnit.HOURS.toSeconds(1))) {
// Reset the cache time to "now"
RepositoryUtil.resetCache(sharedPreferences, "ArtistEvent", artist.first().name)
// Call webservice synchronously
val freshEvents = api.findArtistEvents(artist.first().name).execute().body()
// Update/Insert events in database
bandsInTownDatabase.artistEventDao().upsert(freshEvents)
}
return database.artistEventDao().getEventsByArtistId(artist.first().id)
}
override fun onPostExecute(result: List<ArtistEvent>) {
hideProgress()
showData(result)
}
}
// 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