architecture-components-samples icon indicating copy to clipboard operation
architecture-components-samples copied to clipboard

In the example project BasicRxJavaSample, Activity includes business logic!

Open arifnadeem7 opened this issue 7 years ago • 6 comments

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?

arifnadeem7 avatar Oct 25 '17 11:10 arifnadeem7

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.

ivotai avatar Oct 26 '17 08:10 ivotai

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!

arifnadeem7 avatar Oct 27 '17 07:10 arifnadeem7

.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.

beilo avatar Nov 10 '17 02:11 beilo

AndroidSchedulers.mainThread() is not from Android SDK, it is part of RxAndroid library, you can write your own scheduler and remove AndroidScheduler.

arifnadeem7 avatar Nov 10 '17 06:11 arifnadeem7

but, using observeOn(AndroidSchedulers.mainThread()) in Java is wrong, and I think the switching thread does not have much to do with the model

beilo avatar Nov 10 '17 06:11 beilo

I agree, we can compose this thread switch in the view and then let the ViewModel do the actual subscribe().

arifnadeem7 avatar Nov 10 '17 07:11 arifnadeem7