Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Introduction of ReactiveX

Introduction of ReactiveX

Yuki Funakoshi

February 08, 2016
Tweet

More Decks by Yuki Funakoshi

Other Decks in Programming

Transcript

  1. val a = Observable.from(arrayOf(1,2,3,4,5)) val b = Observable.from(arrayOf(6,7,8,9,10)) Observable.merge(a, b)

    .filter { it % 2 == 0 } .subscribeOn(Schedulers.newThread()) .subscribe { println(it) } 2 4 6 8 10
  2. val a = Observable.create<Int> { subscriber -> subscriber.onNext(2); subscriber.onCompleted(); }

    val b = Observable.from(arrayOf(6,7,8,9,10)) Observable.merge(a, b) .filter { it % 2 == 0 } .subscribe { println(it) } 2 6 8 10
  3. data class Item(val id: String, val title: String) interface ItemService

    { @GET("/api/v2/items") fun items(): Observable<List<Item>> } fun api() { val retrofit = Retrofit.Builder() .baseUrl("http://qiita.com") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); val service = retrofit.create(ItemService::class.java) service.items().subscribe { it.map { println(it.title) } } } https://gist.github.com/bl-lia/49130ad9d9730c826d02
  4. interface ItemDataStore { fun items(): Observable<List<Item>> } // Singleton Class

    object ItemCache : ItemDataStore { override fun items(): Observable<List<Item>> { // Return cached items } fun reset(newItemList: List<Item>) { // Replace cached items } fun isCached(): Boolean { // Cache data exists? } } class ItemApi(cache: ItemCache) : ItemDataStore { val cache = cache override fun items(): Observable<List<Item>> { val retrofit = Retrofit.Builder()...build() val service = retrofit.create(ItemService::class.java) return service.items().doOnNext { cache.reset(it) } } } https://gist.github.com/bl-lia/23023d968ab884708f30
  5. class ItemStoreFactory { val cache = ItemCache fun create(): ItemDataStore

    { if (cache.isCached()) { return cache } return ItemApi(cache) } } fun main(args : Array<String>) { ItemStoreFactory().create().items() } https://gist.github.com/bl-lia/23023d968ab884708f30