samedi 21 mai 2022

MVVM Service Layer?

Is it good practice to implement a service layer with MVVM?

In my case, I split my business logic into a service and a model. A service takes a model and a repository as a dependency and calls functions on each depending on what the ViewModel tells it to do. Instinctively, this reminds me of an Anemic Domain Model, but I believe it isn't as my Models don't have getters and setters, they have functions such as like() and unlike() to mutate its properties internally.

Example of what I am implementing:

class PostViewModel with ViewModel {
  final IPostService _service;

  PostViewModel(this._service);

  bool get isLiked => _service.isLiked;
  int get likeCount => _service.likeCount;

  void like() {
    _service.like();
    notifyListeners(); // update views
  }
}
class PostService implements IPostService {
  final PostModel _model;
  final IPostRepository _repository;

  PostService(this._model, this._repository);

  @override
  int get likeCount => _model.likeCount;

  @override
  bool get isLiked => _model.isLiked;


  @override
  Future<void> like() async {
    _model.like(); // tell model that this post was liked
    _repository.like(); // tell server that this post was liked
    // more complex logic will go in here in the future
  }
class PostModel {
  final String _id;
  ... other properties

  int get likeCount => _likeCount;
  bool get isLiked => _isLiked;

  void like() {
    _likeCount++;
    _isLiked = true;
  }
}

I like this implementation because it lets me plug in features to ViewModels whenever I need, so if I need to reuse this Post logic, I can do so easily. One downside though is that I have to write so many getters.

Aucun commentaire:

Enregistrer un commentaire