Created
May 13, 2020 17:31
-
-
Save krossovochkin/33a194a20f2575cc460432f8da67d2da to your computer and use it in GitHub Desktop.
RxJava ViewModelScope
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
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