Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate application logic from network layer in Android using Retrofit 2

I am new in Android and Retrofit and I am facing one problem.

I want to have my lets say "ServerCommunication" class (singelton) where all Retrofit magic is done and it will have public methods where REST calls are done.

I want to use this "ServerCommunication" instance in my activities to call Rest service, but thats it. Application logic should be done in activity. So this way some activity Login calls method Login(POJORequest) in "ServerCommunication) where actual REST call via Retrofit framework is done and some POJOResponse is returned. So Activity doesn't care about REST communication while ServerCommunication doesn't care about what logic that should be applied to response from REST service since.

With retrofit 2 I do not understand how I can block Activity to wait for response from retrofit and how it can be returned. Well, I might think I can use some callback methods in activity so those methods can be called from ServerCommunication" in OnPostExecute() to apply some logic based on data from response. It's just I think it should be simpler approach.

Well, to clarify all this mess above imagine simple case: You have data in you main activity, you pass this data to your communication class where REST call is done and response is received. This response must be validated in order to continue. And you want this validation to be done in main activity and NOT in communication class.

What is pattern to do that in Android with Retrofit2 ?

Thank you in advance

like image 955
Tony Avatar asked Jan 27 '16 16:01

Tony


1 Answers

What I normally do:

  • Create your Interface (where you have all your REST methods - GET & POST etc)
  • Create a class that does the actual calls with corresponding methods (refer to the interface REST methods). I would call it something like ServiceAPIImplementor. This is where you actually create your Retrofit adapter.
  • In your activity, create an instance of your implementor class and call the methods and pass the expected arguments.
  • After calling the methods, you should probably show a progress dialog to let the user know that something is going on.
  • When the onResponse or onFailure method is called, use an Event pattern (EventBus library?) to notify the activity that the network operation has been completed. Once the activity has received the notification, it should then dismiss the progress dialog and update the UI accordingly - with the newly received data or completed operation (expected outcome).

I hope this helps you get closer to what you are trying to achieve!

like image 160
Eenvincible Avatar answered Sep 20 '22 10:09

Eenvincible