Retrofit Implementation using MVVM architecture

Profiles:
Linkedin: https://www.linkedin.com/in/nikitha-gullapalli/
Github: https://github.com/nikitha2/EXMPLE_RETROFIT_with-arch-components.git

Retrofit is an awesome type-safe HTTP client for Android and Java built by awesome folks at Square. Retrofit makes it easy to consume JSON or XML data which is parsed into Plain Old Java Objects (POJOs).

Implementation:

Simple Retrofit implementation is 6 step:

Step 1: POJO class with fields one wants to read from the API network call.

public class RetroPhoto {

@SerializedName("albumId")
private Integer albumId;
@SerializedName("id")
private Integer id;
@SerializedName("title")
private String title;
@SerializedName("url")
private String url;
@SerializedName("thumbnailUrl")
private String thumbnailUrl;

public RetroPhoto(Integer albumId, Integer id, String title,
String url, String thumbnailUrl) {
this.albumId = albumId;
this.id = id;
this.title = title;
this.url = url;
this.thumbnailUrl = thumbnailUrl;
}

//Setter and getter methods
}

Step 2: Define RetrofitClientInstance singleton class to get an instance of Retrofit. Define the base URL

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClientInstance {

private static Retrofit retrofit;
private static final String BASE_URL = "https://jsonplaceholder.typicode.com";

public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}

Step 3: Create a service class (similar to DAO in Room) with

import retrofit2.Call;
import retrofit2.http.GET;

public interface GetDataService {

@GET("/photos")
Call<List<RetroPhoto>> getAllPhotos();
}

Step 4: Define the Repository to make the network call.

call.enqueue makes sure the network call is performed on another thread rather than the main Thread. onResponse() method is called when the call is successful and onFailure() is called on failure.

Step 5: Now call the repository from ModelView

import java.util.List;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import androidx.recyclerview.widget.RecyclerView;

public class MainViewModel extends ViewModel {
Repository repository;

public MainViewModel(Context context) {
repository = new Repository(context);
}

public MutableLiveData<List<RetroPhoto>> getTasks() {
return repository.getTasks();
}

}

Step 6: Observe the ModelVew data from activity. in other words, observe the live data to update the UI screen every time there is a change in cache data.

private void setupViewModel() {
MainViewModelFactory factory = new MainViewModelFactory(this);
MainViewModel viewModel = ViewModelProviders.of(this,factory)
.get(MainViewModel.class);
viewModel.getTasks().observe(this,new Observer<List<RetroPhoto>>(){
@Override
public void onChanged(List<RetroPhoto> retroPhotos) {
if(retroPhotos.isEmpty()){
progressDoalog.dismiss();
}
else{
progressDoalog.dismiss();
generateDataList( retroPhotos );
}
}
});
}

Conclusion:

Retrofit is an amazing library to make network calls. It simplifies the code and makes it easier to expand the codebase in a cleaner way. Volly is another third party library that we can use for network calls.

References:

Check out the below article for more information. I took the example I mentioned in this article from the below article and implemented it.

--

--

--

Mobile app developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Checklist for bringing old projects up-to-date

Android 11/Android R 已經不支援Pixel(sailfish)

Save State By Using RxJava or Kotlin Flow

Recycler view, power of asynchronous view holders creation

Gitlab CI/CD for Android-Part 1

RecyclerView Ain’t so Tough

Using (deprecated) synthetic properties on Views

Listeners in DialogFragments

A beautiful photo of a lake by a forest

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nikitha Gullapalli

Nikitha Gullapalli

Mobile app developer

More from Medium

How to add AR face filters to your Android app

Setup Cordova for Android

Setup Firebase for Android development [2022]

How to send SMS programmatically from an Android application