Skip to content

Instantly share code, notes, and snippets.

@umair13adil
Last active March 8, 2018 06:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umair13adil/4379fac040bddae354d6a38a08764369 to your computer and use it in GitHub Desktop.
Save umair13adil/4379fac040bddae354d6a38a08764369 to your computer and use it in GitHub Desktop.
Flowables (RxJava2) with Realm
var tasksList: RealmList<Tasks>
tasksList = RealmList()
getPendingTasks(3)
.flatMapIterable { it -> it }
.concatMap { task ->
getPendingSubTasks(task.id)
.doOnNext {
//Here we are binding subtasks to individual task item
bindChildTasks(it, task)
}
}.toList()
.subscribeOn(looperScheduler)
.unsubscribeOn(looperScheduler)
.observeOn(looperScheduler)
.doOnSubscribe {
showLoading("")
}.subscribeBy( // named arguments for lambda Subscribers
onError = {
it.printStackTrace()
}, onSuccess = {
/Finalized Composed list will be used on MainThread in this callback
loadTasks()
}
)
//Child tasks will be added using Realm transaction
fun bindChildTasks(subTaskList: List<SubTasks>, task: Tasks) {
if (subTaskList.size > 0) {
Realm.getDefaultInstance().executeTransaction {
val realmList = RealmList<SubTasks>()
realmList.addAll(subTaskList)
task.subTasksList = realmList
}
}
}
//Our composed list will be fetched in this observable:
fun loadTasks() {
getPendingTasks(3)
.subscribeOn(AndroidSchedulers.mainThread())
.unsubscribeOn(AndroidSchedulers.mainThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribeBy( // named arguments for lambda Subscribers
onNext = {
tasksList.addAll(it)
},
onError = {
it.printStackTrace()
},
onComplete = {
//We populate our RecyclerView here
setUpAdapter()
hideLoading()
}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment