Created
February 7, 2016 08:03
-
-
Save bl-lia/23023d968ab884708f30 to your computer and use it in GitHub Desktop.
Cache Control Sample
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
import retrofit2.GsonConverterFactory | |
import retrofit2.Retrofit | |
import retrofit2.RxJavaCallAdapterFactory | |
import retrofit2.http.GET | |
import rx.Observable | |
class CacheControlSample { | |
data class Item(val id: String, val title: String) | |
interface ItemService { | |
@GET("/api/v2/items") | |
fun items(): Observable<List<Item>> | |
} | |
interface ItemDataStore { | |
fun items(): Observable<List<Item>> | |
} | |
// Singleton Class | |
object ItemCache : ItemDataStore { | |
var itemList = listOf<Item>() | |
override fun items(): Observable<List<Item>> { | |
return Observable.just(itemList); | |
} | |
fun reset(newItemList: List<Item>) { | |
itemList = newItemList | |
} | |
fun isCached(): Boolean { | |
return itemList.size > 0 | |
} | |
} | |
class ItemApi(cache: ItemCache) : ItemDataStore { | |
val cache = cache | |
override fun items(): Observable<List<Item>> { | |
val retrofit = Retrofit.Builder() | |
.baseUrl("http://qiita.com") | |
.addConverterFactory(GsonConverterFactory.create()) | |
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) | |
.build(); | |
val service = retrofit.create(ItemService::class.java) | |
return service.items().doOnNext { cache.reset(it) } | |
} | |
} | |
class ItemStoreFactory { | |
val cache = ItemCache | |
fun create(): ItemDataStore { | |
if (cache.isCached()) { | |
return cache | |
} | |
return ItemApi(cache) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment