architecture-components-samples
architecture-components-samples copied to clipboard
In the example project BasicRxJavaSample, Activity includes business logic!
I see this code in UserActivity.java
mDisposable.add(mViewModel.getUserName()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(userName -> mUserName.setText(userName),
throwable -> Log.e(TAG, "Unable to update username", throwable)));
Why should the Activity manage Disposable? Also subscribeOn, observeOn and the actual subscribe method should go in ViewModel, shouldn't they?
What is the best way to circumvent this?
ViewModel has two advantage: use onCleared
method to dispose,survive after lifecycleOwner recreating , still hold the data.
This example does not override onCleared
method and send request every time lifecycleOwner onStart
.
It even shouldn't use ViewModel.
Yes ViewModels look like an unnecessary overhead in this particular example, they do too little and they should manage Disposable which right now they aren't!
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
It is for the viewModel
to be able to use junit4
directly in the test module
, and try not to import android modules
.
AndroidSchedulers.mainThread() is not from Android SDK, it is part of RxAndroid library, you can write your own scheduler and remove AndroidScheduler.
but, using observeOn(AndroidSchedulers.mainThread())
in Java
is wrong, and I think the switching thread does not have much to do with the model
I agree, we can compose this thread switch in the view and then let the ViewModel do the actual subscribe().