Bartando
Bartando

Reputation: 748

MVVM - Where to load data from internet

I'm trying to use this MVVM for my android app. I've done many apps, but I'm trying to step up on another level and trying to use the MVVM. But I need to understand where I should load the data from internet. I'm using RxJava, but I'm not sure if I should load data only in ViewModel. If so then where do I set the data. I'm using Databinding from google, but I don't wanna set data in xml through viewModel. I want to set it from the java file.

I'm sorry if I miswrote something, post an answer and I will try to fill out any required informations.

Upvotes: 4

Views: 2008

Answers (2)

Manas Chaudhari
Manas Chaudhari

Reputation: 276

"Triggering a DataLoad" is part of presentation logic. Hence, this should belong in ViewModel.

Details about "How data is loaded" for example, networking logic, does not belong to the ViewModel layer. I highly recommend using Retrofit as you are already using RxJava.

As rx.Observableand databinding.ObservableField are very similar, you can convert them from one form to another. I have written a library that allows you to do this. See FieldUtils.java for an implementation.

Either ways, assuming you have a DataService interface/class:

public interface DataService {
   Observable<String> loadSomeData();
}

you can build your ViewModel as follows:

public class ExampleViewModel {
    ObservableField<String> title;

    public ExampleViewModel(DataService dataService) {
        this.title = FieldUtils.toField(dataService.loadSomeData());
    }
}

Then, you can display this in your View using Data Binding syntax

<TextView
    android:text="@{viewModel.title}" />

I recently blogged about using RxJava with MVVM. I showed an app which loads a list of events from Github using Retrofit and displays them in a RecyclerView. This has been implemented in MVVM.

Article link: MVVM using RxJava + Data Binding example: Loading data using Retrofit

A more complicated example which also shows a loading indicator and error: DataLoadingViewModel.java.

Upvotes: 1

Alex Shutov
Alex Shutov

Reputation: 3282

There is two similar architectural patterns - MVP and MVVM. The main difference is that in MVP parttern Presenter desides how to display data, but in MVVM pattern View receives Model and renders itself (takes data from model). Classical MVVM example is view bindig. But the point is - nomatter what pattern you use, you should obtain all data in Model - and place all your business logic in Model too.

Upvotes: 0

Related Questions