Last active
February 25, 2017 07:09
-
-
Save minibugdev/0465eb642d069e08a27adbcc6cbe64f6 to your computer and use it in GitHub Desktop.
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
// สร้าง Observable ของ API | |
var observable = service.getWeather(CITY_NAME, getString(R.string.api_key)) | |
// Delay 1 วินาทีเพื่อให้ API ทำงานช้ากว่า Cache เพื่อให้เห็นภาพการทำงานง่ายขึ้น | |
.delay(1L, java.util.concurrent.TimeUnit.SECONDS) | |
// เขียนข้อมูลลง Realm | |
.subscribeOn(Schedulers.io()) | |
.observeOn(Schedulers.computation()) | |
.map { this.writeToRealm(it) } | |
// ค้นหาข้อมูลด้วยชื่อเมืองที่ได้มา API จากใน Cache | |
.observeOn(AndroidSchedulers.mainThread()) | |
.map { this.readFromRealm(it) } | |
// ค้นหาข้อมูลด้วยชื่อเมืองที่กำหนดไว้ (CITY_NAME = "Bangkok") จากใน Cache | |
val cachedWeather = readFromRealm(CITY_NAME) | |
if (cachedWeather != null) { | |
// ถ้ามีข้อมูลใน Cache ทำการ Merge เข้ากับ Observable ของ API | |
observable = observable.mergeWith(Observable.just(cachedWeather)) | |
} | |
// สั่ง Subscrbe (คำสั่งด้านบนทั้งหมดจะยังไม่ทำงาน จนกว่าจะสั่ง Subscribe นะจ๊ะ) | |
subscription = observable.subscribe( | |
{ this.display(it) }, // onNext() | |
{ this.processError(it) } // onError() | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment