I am fetching images by using retrofit with MVVM Architecture. Now I want to add some features like image editing or compression and uploading.
My question is . For MVVM architecture, is the business logic for these features a use case?
domain
- usecase
- ImageCompressionUseCase.kt
- UploadImageUseCase.kt
- usecase
ui
- ImageCompressionViewModel.kt
- ImageCompressionFragment.kt
- UploadImageViewModel.kt
- UploadImageFragment.kt
My brain says it's use cases but I'm a bit hesitant :)
ImageCompressionUseCase.kt
@Singleton
class ImageCompressionUseCase @Inject constructor(@ApplicationContext private val context: Context) {
suspend operator fun invoke(name:String) : Result<File> = runCatching {
withContext(Dispatchers.IO){
val output = File(context.filesDir,"$name.png")
// some logic to image compression
output
}
}
}
ImageCompressionViewModel.kt
@HiltViewModel
class ImageCompressionViewModel @Inject constructor(private val imageCompressionUseCase: ImageCompressionUseCase) : ViewModel() {
private val _isLoading = MutableLiveData<Boolean>()
val isLoading get() = _isLoading
private val _data = MutableLiveData<Result<File>>()
val data get() = _data
fun start(){
viewModelScope.launch {
_isLoading.value = true
_data.value = imageCompressionUseCase("example_name")
_isLoading.value = false
}
}
}
CodePudding user response:
You are right - use case is used for single actions done within a single feature. Your features - Compression, editing and uploading photos - code should be accommodated in the Use Cases preferably in one use case per action.
What previously the plain MVVM did inside the ViewModel is now done in the use cases.
This way it makes code easy to understand and you can also use Compression or Editing feature use cases in different ViewModels without having to duplicate the code.