Skip to content

Instantly share code, notes, and snippets.

@krossovochkin
Created May 13, 2020 17:31
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 krossovochkin/33a194a20f2575cc460432f8da67d2da to your computer and use it in GitHub Desktop.
Save krossovochkin/33a194a20f2575cc460432f8da67d2da to your computer and use it in GitHub Desktop.
RxJava ViewModelScope
class TestViewModel : MyViewModel() {
init {
scope.launch(
Observable.just("10")
.subscribe { println("Something") }
)
Observable.just("10")
.doOnNext { println("something") }
.launchIn(scope)
// beware, still possible to run without scope
Observable.just("10")
.subscribe { println("Something") }
}
}
abstract class MyViewModel {
private val observers = mutableMapOf<String, Closeable>()
fun onDestroy() {
observers.values.forEach(Closeable::close)
observers.clear()
}
fun setObserver(key: String, value: Closeable) {
observers[key] = value
}
fun getObserver(key: String): Closeable? {
return observers[key]
}
}
interface MyScope : Closeable {
fun launch(job: Disposable)
}
private const val TAG_SCOPE = "TAG_SCOPE"
val MyViewModel.scope: MyScope
get() {
val scope = getObserver(TAG_SCOPE) as? MyScope
if (scope != null) {
return scope
}
val newScope = object : MyScope {
val compositeDisposable = CompositeDisposable()
override fun launch(job: Disposable) {
compositeDisposable.add(job)
}
override fun close() {
compositeDisposable.clear()
}
}
this.setObserver(TAG_SCOPE, newScope)
return newScope
}
fun <T> Observable<T>.launchIn(scope: MyScope) {
return scope.launch(this.subscribe())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment