MVVM - Implementing Google Maps and having the context in ViewModel?

Viewed 8408

So I'm learning MVVM, loving it.

But.. my problem so far has been the following:

  • Implementing google maps with MVVM. (Do I do it on the activity or the viewmodel? I was only able to implement it on the activity..)

  • Especially CONTEXT.. Is it okay to pass it along like below?

I'm using this library.

This is my ViewModel:

public class DashboardViewModel implements ViewModel {

public final ObservableField<String> dashButton = new ObservableField<>("");
public final Action onRandomSearch;
private Context context;



public DashboardViewModel(Context context) {
    this.context = context;

    onRandomSearch = () -> {
        String randomString = UUID.randomUUID().toString();
        String randomQuery = randomString.substring(0, 3) + " " + randomString.substring(5, 8);
        dashButton.set(randomQuery); //JUST TO TEST
    };
}

}

This is my activity:

public class DashboardActivity extends MvvmActivity {
@NonNull
@Override
protected ViewModel createViewModel() {
    loadMap();

    return new DashboardViewModel(this);
}

@Override
protected int getLayoutId() {
    return R.layout.activity_dashboard;
}

private void loadMap() {
    SupportMapFragment mapFragment =
            (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    startLocation();

...

Now, in order to get google maps working on my application I had to implement OnMapReadyCallback, like so:

public class DashboardActivity extends MvvmActivity implements OnMapReadyCallback

I need to communicate with the method to get current location, which I implemented inside DashboardActivity..

Should I migrate the logic to get the map working inside the ViewModel?

I'm a little lost here.

1 Answers
Related