'How to improve Android MVVM Tic-Tac-Toe

I was following this tutorial (https://academy.realm.io/posts/eric-maxwell-mvc-mvp-and-mvvm-on-android/) implementing different patterns (MVC, MVP and MVVM) in Kotlin for a Tic Tac Toe game. At the MVVM part, the example does the following:

public class TicTacToeViewModel implements ViewModel {

    private Board model;

    public final ObservableArrayMap<String, String> cells = new ObservableArrayMap<>();
    public final ObservableField<String> winner = new ObservableField<>();

    public TicTacToeViewModel() {
        model = new Board();
    }

[...]
    public void onClickedCellAt(int row, int col) {
        Player playerThatMoved = model.mark(row, col);
        cells.put("" + row + col, playerThatMoved == null ? 
                                                     null : playerThatMoved.toString());
        winner.set(model.getWinner() == null ? null : model.getWinner().toString());
    }

[...]

}

Considering that the model, of class Board, already has an attribute board (that is an Array < Array < Cell > >), what's the point for replicate that board with other variable at the TicTacToeViewModel? Is not possible refer to the model board directly with an LiveData or Observable class? Same for the winner

I've saw as well many implementations on Github doing the same, and I am wondering if that's happening due to heritance of the article or in fact has to be this way when the data is kind of complex (a 2D array in this particular case)

I'll appreciate any comments or thoughts on this. Thanks in advance!



Solution 1:[1]

I skimmed the tutorial and the github page, and in short I would recommend not following that tutorial :)

Looking at the source code on github, it's clearly an unfinished project. For example, the one layout in the entire project just has a "Hello, world!" TextView in it, which is boilerplate code you get just for creating an Android project...

But to answer your question in a more general sense, you don't necessarily need redundant data structures to represent the board. One reason you might want them is to differentiate between what is displayed to the user versus what the app uses to track the state of the game. For example, the user sees 'O's and 'X's, but perhaps your ViewModel or backing data structure tracks the board as a binary string for the sake of memory and performance (imagine scaling the game out to a much larger board.) But you could probably just create a function to convert the underlying data to a user-friendly format for display, without the need for redundant data structures.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1