Thursday, October 3, 2019

Custom cell class datasource in MVVM design pattern



We generally pass a model to cell to configure/render and the reason behind it is, instead of passing multiple parameters, we can have a model to be passed as parameter.


Let’s take a below cell for example which is having 4 labels and in MVVM design pattern, viewmodels build and gives model to cell in cellForRowAt in viewcontroller.





This seems/sounds familiar as this is what we have been doing.
But, there are flaws in this approach.

  1. What If I want to reuse the cell?
  2. In MVVM design pattern view(in this case cell) should not hold a model(Agree?)



I can not reuse the cell efficiently as this cell is tightly coupled with a model.

First in place, this poor cell is having 4 labels and technically needs 4 stings to display. As simple as that. Isn’t it?

Then why to pass a model and create a tight coupling.

Instead of passing a model, Cell can have a datasource implemented like below.




Now cell configuration happens based on the ProductCellDataSource protocol. That means any model that confirms to this protocol can be passed to cell configure method to render the cell.




In other words, cell is just asking to send me the data as per my protocol and it is saying I am not literally worried about the model you are sending as long as it confirms to my datasource protocol.




With this approach, cell will not have any tight coupling with models(MVVM basic rule) and it can be reused by passing any model which confirms to it’s datasource protocol.

Hope this post is useful. Feel free to comment incase of any queries.


5 comments:

  1. The blog was absolutely fantastic! Lots of great information . Keep updating the blog.

    Hire Affordable Xamarin Developer
    Xamarin Developers in Frisco

    ReplyDelete
  2. Thanks for sharing great post. I really like this post.

    If you want to make custom website & application you can contact us on our Web Design Company and Top iOS App Development Company anytime.

    ReplyDelete
  3. Great post! This is something new to my knowledge. Keep updated with awesome content like this. iOS Development

    ReplyDelete
  4. Bookmarked this article to train freshers, Thanks Mobile app development

    ReplyDelete
  5. Thanks for sharing the useful information about Custom Cell Class Data Source in MVVM. If you are looking for an Mobile App Development Company In India. Then you can go with Lucid Outsourcing Solutions they have team of expertise in various technologies which can perform various tasks in your projects.

    ReplyDelete