Skip to content

Instantly share code, notes, and snippets.

@minibugdev
Last active February 25, 2017 07:09
Show Gist options
  • Save minibugdev/0465eb642d069e08a27adbcc6cbe64f6 to your computer and use it in GitHub Desktop.
Save minibugdev/0465eb642d069e08a27adbcc6cbe64f6 to your computer and use it in GitHub Desktop.
// สร้าง 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