Search code examples
androidmvvmrx-javarx-java2android-mvvm

MVVM with RxJava without DataBinding


After reading a lot of articles about MVVM and RxJava, I need to implement the simplest demo to catch the idea well without using DataBinding

But I got stuck in the way how the ViewModel will notify the View (Activity) with the list of data

My ViewModel contain fetchGitHub() which using RxJava in this way

io.reactivex.Observable<List<Repo>> reposReturnedObservable = githubClient.reposForUser(user);

    reposReturnedObservable
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<List<Repo>>() {
                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }

                @Override
                public void onSubscribe(Disposable d) {
                    compositeDisposable.add(d);
                }

                @Override
                public void onNext(List<Repo> repos) {
                    data = repos;
                }
            });

What is the missing lines here to update the view with the data

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    viewModel = new ViewModel();
    viewModel.fetchGitHub("square");

}

Solution

  • fetchGitHub() should return an Observable, so that the Activity can subscribe to it.

    ViewModel:

    public class ViewModel {
    
        public Observable<List<Repo>> fetchGitHub(String userName) {
            return githubClient.reposForUser(user);
        }
    
    }
    

    Activity:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        TextView listSizeTextView = findViewById(R.id.listSizeTextView);
    
        viewModel = new ViewModel();
        viewModel.fetchGitHub("square")
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(list -> listSizeTextView.setText("list size: " + list.size()));
    }
    

    Above example does not store the subscription to provide you with a simplified answer but in real practice, make sure to clear subscriptions like you did in your example.