Skip to content

Instantly share code, notes, and snippets.

@hkhc
Last active March 12, 2019 17:23
Show Gist options
  • Save hkhc/69481aac39c2f4fdfdceabbb2a5bf8c4 to your computer and use it in GitHub Desktop.
Save hkhc/69481aac39c2f4fdfdceabbb2a5bf8c4 to your computer and use it in GitHub Desktop.
rxjava to replace asynctask
// Assume you have three class to represent state of operations,
// and they have a common base class
sealed class BaseClass {
class ClassStart: BaseClass()
class ClassProgress(var percent: Int): BaseClass()
class ClassStop: BaseClass()
}
// Define the job here. It does not really execute it
fun jobObservable() =
Observable
.just<BaseClass>(BaseClass.ClassStart())
.observeOn(Schedulers.io())
.concatMap { c ->
Observable.create<BaseClass> { emitter ->
(1..10).forEach {
// do your background job here
emitter.onNext(BaseClass.ClassProgress(it))
}
}
}
.observeOn(AndroidThread.mainThread())
.concatMap<BaseClass> { Observable.just(BaseClass.ClassStop()) }
.subscribeOn(AndroidSchedulers.mainThread())
// Actually do the job
fun doTheJob() {
val disposable = jobObservable().subscribe {
when(it) {
is BaseClass.Class1 -> System.out.println("Start")
is BaseClass.Class2 -> System.out.println("Progress ${it.percent}")
is BaseClass.Class3 -> System.out.println("Finish")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment