Reputation: 15
I have created a network client app (using Retrofit) where I call for network request and response in the activity. I learned that it is a bad practice. If anyone can suggest that what can be a good design pattern that I can follow to do such an operation?
Upvotes: 0
Views: 142
Reputation: 41
Create a RetrofitClient Class like this
public class RetrofitClient {
public static final String BASE_URL = "YOUR BASE URL HERE";
public static RetrofitClient mInstance;
private Retrofit retrofit;
public static RetrofitClient getInstance() {
if (mInstance == null)
mInstance = new RetrofitClient();
return mInstance;
}
private RetrofitClient() {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public ApiInterface getApiInterface() {
return retrofit.create(ApiInterface.class);
}
public interface ApiInterface {
@GET("api_name_here")
Call<ResponseBody> methodName();
}
}
Repository class
public class MyRepository {
private static MyRepository mInstance;
public static MyRepository getInstance() {
if (mInstance == null)
mInstance = new MyRepository();
return mInstance;
}
private MyRepository(){
}
private LiveData<T> getData(){
MutableLiveData<T> liveData = new MutableLiveData<>();
RetrofitClient.getInstance()
.getApiInterface()
.methodName()
.enqueue(new Callback<T>() {
@Override
public void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {
liveData.setValue(response.body());
}
@Override
public void onFailure(@NonNull Call<T> call, @NonNull Throwable t) {
// handleFailure
}
});
return liveData;
}
}
ViewModel Class
public class MyViewModel extends ViewModel{
private MyRepository myRepository;
public MyViewModel(){
myRepository = MyRepository.getInstance();
}
public LiveData<T> getData(){
return myRepository.getData();
}
}
Then in your Activity or fragment
MyViewModel myViewModel = new ViewModelProvider(this).get(MyViewModel.class);
myViewModel.getData().observe(this, new Observer<T>() {
@Override
public void onChanged(T t) {
// handle your data here...
}
});
Upvotes: 0
Reputation: 373
For Start if you have to create an app from scratch, possibly try to follow one architecture since you are looking for network calls,
You can Use MVVM for best practice and it also handle the api request in best way possible As you can see from figure, This architecture, basically separates the view(UI) from view Model(logic of view)
It's up to you how you want to develop the app, means you can skip the repository and handle the network calls in view models or else you can create a single repository class and place all the network related stuffs i.e: network call and similar stuff.
reference tutorial : https://learntodroid.com/consuming-a-rest-api-using-retrofit2-with-the-mvvm-pattern-in-android/
Upvotes: 1