{"id":898,"date":"2019-12-28T07:30:52","date_gmt":"2019-12-27T21:30:52","guid":{"rendered":"https:\/\/learntodroid.com\/?p=898"},"modified":"2021-01-13T09:46:24","modified_gmt":"2021-01-12T23:46:24","slug":"consuming-a-rest-api-using-retrofit2-with-the-mvvm-pattern-in-android","status":"publish","type":"post","link":"http:\/\/10.0.0.14:32769\/consuming-a-rest-api-using-retrofit2-with-the-mvvm-pattern-in-android\/","title":{"rendered":"Consuming a REST API using Retrofit2 with the MVVM Pattern in Android"},"content":{"rendered":"\n

Design patterns are important to help us create cleaner more extensible code with a clear separation of concerns. Understanding how all the Android Jetpack architecture components fit together in the Model View ViewModel (MVVM) design pattern is not a simple task and adding integrating with an API to the mix can increase the learning curve. After doing some research on how to use Retrofit2 to consume an API while following the MVVM pattern, I have put together this tutorial to share what I have learnt.<\/p>\n\n\n\n

To consume a REST API using Retrofit2 using the MVVM pattern in Android the you will need to complete the following steps.<\/p>\n\n\n\n

  1. Allow permission to use the internet in the app manifest<\/strong><\/li>
  2. Obtain developer dependencies for Retrofit2 and the various Jetpack libraries enabling MVVM in Android using Gradle<\/strong><\/li>
  3. Create the model to handle the API response<\/strong><\/li>
  4. Use Retrofit2 to create an interface of the API<\/strong><\/li>
  5. Create a repository and consume the API within the repository using Retrofit2<\/strong><\/li>
  6. Create the ViewModel and connect it to the repository<\/strong><\/li>
  7. Create the View and connect it to the ViewModel to make the API call via the repository<\/strong><\/li><\/ol>\n\n\n\n

    In the article I will take you through a tutorial of consuming the REST API offered by Google for Google Books using Retrofit2 inside an Android app architected using the Model View ViewModel design pattern in Java.<\/p>\n\n\n\n

    All of the code samples that will be shown in this article in the tutorial section are available publicly on GitHub in the Learn To Droid<\/a> MVVM REST API repository<\/a>. <\/p>\n\n\n\n

    Before we jump into the tutorial I will also cover the following.<\/p>\n\n\n\n