People say business logic should handled in domain layer.
But I don't exactly understand what is business logic in Android.
In my project I cache data when API request is successful.
And if API Request got failed, get local data.
In my understand It can be a kind of business rule.
1. API request
2. If API request is failed load data from local.
I think this logic should be done in the repository.
But business logic should handle in domain layer.
Am I misunderstanding the business logic?
The business logic is refereed to if
s and else
s you have after you receive the data from the API. Let's say that you want to load an image using Picasso
. The url is:
https://.../imageId.jpg
But first you will need to fetch this object which has an id attached to it's JSON:
{
"id" : "1234123",
"name" : "SomeName"
}
Well, first you would need to fetch this:
val request = repository.fetchTheObject()
//let's assume the result is successful
//start of the business logic
val imageId = request.id
if(id == WHATEVER){
val url = "someUrl/${id}.jpg"
someMutableLiveData.postValue(url)
}else{
showSomeError()
}
//end of business logic
And then in your fragment you just receive the final result:
viewModel.someMutableLiveData.observe(this, Observer{
Picasso.get().load(it).into(imageView)
})
In other words:
Business logic is all the actions you need to perform to the data you receive from the source of truth (database, files, network API etc) in order to achieve a desirable result
In case of Android:
Fragment
/Activity
for interacting with the userViewModel
for business logic (sometimes when you have tones of if
s/else
, a lot of for-loops etc, Google suggests to use a Presenter attached to a ViewModel, never done it)In your case the business logic is exactly what you describe: If your request fails then get local data, this is a business logic of the app.
I think this logic should be done in the repository.
Well you can do that, and I have seen many examples like that and it really depends, sometimes could be correct. But in case when you are using a ViewModel
in order to avoid all Transformations
you can just handle it in the ViewModel
instead of the Repository
.