7

I'm trying to follow the MVVM pattern in a new App I'm currently writing.

Basically it gets a list of items in JSON from my REST-Backend and displays it in a RecycleView inside my fragment.

I created a repository, which fetches the data and hands it over to the ViewModel which has LiveData which is observed by the fragment.

That all works fine.

But: Every item also has a url for an icon. When the list is fetched, for every item I want to load the icon from this url into a ImageView.

Actually I am using Glide to directly (asynchronously) load the icon into the corresponding ImageView - which is good for UX and performance (in my opinion), since the user already sees data while the icons load in the background

My question:

Does using Glide directly in the fragment break the MVVM pattern?

What's an alternative approach to that?

E.g. loading the icons in the Repository, updating the RecycleView every time a icon is fetched (bad performance)?

Ümañg ßürmån
  • 9,695
  • 4
  • 24
  • 41

3 Answers3

2

In my opinion, I think it break MVVM but I think it still ok

Example: If we don't use any library for load image from url, we will create a function to get the bitmap from url (like ImageRepository#getImageBitmap(url)), after we receive the bitmap, we will use it to display into ImageView.
Why getImageBitmap(url) should be inside Repository? // because it get data from server

However, image loading library handle all for us and it support many great things and also loading image from url just a small task (and we don't need to test it if we using library). Therefore, I think we can load image inside View (Activity,Fragment,...) to make coding easier without any problem.
If we use another approach (like your approach), code will become more complex and also we need more time to test.

This is just my opinion, hope it help

Linh
  • 57,942
  • 23
  • 262
  • 279
  • "Why getImageBitmap(url) should be inside **Repository**? because it get data from server". But it's data access, I think it's **DAO**'s responsibility. – Arash Dec 11 '18 at 10:40
2

you can use BindingAdapters to set the image from XML itself. I think it's a much more cleaner approach, so that UI related changes goes with inside the XML

@BindingAdapter("imageUrl")
fun setImageUrl(imageView: ImageView, url: String?) {
GlideApp.with(imageView)
    .load(url)
    .diskCacheStrategy(DiskCacheStrategy.ALL)
    .into(imageView)
}
gprathour
  • 14,813
  • 5
  • 66
  • 90
Abraham Mathew
  • 2,029
  • 3
  • 21
  • 42
1

Loading an image is something called "low level detail". In other words it's something that Architecture should not care about. Hence If you use Glide or Picasso it's not relevant to Architecture of the app. Based on this your current state is "ok", however your suggestion for alternative way of doing thing can cross so many red lines. Skim through Uncle Bob's Clean Architecture for more details.

shervinox
  • 166
  • 1
  • 11