Search code examples
androidkotlindtouse-case

Dto map and use-case


how can I make Dto map and pass it to the use-case using clean architecture in android kotlin

i tried to make an object class and pass it to the use-case but it didn't work


Solution

  • Note that I will use HILT for dependency injection ... you can use any di library.

    You can make a base interface mapper for objects like this:

    interface mapper <T,R> {
       fun map(t: T): R
    }
    

    Then create a class that implements Mapper interface:

    class ProductMapper @Inject constructor() : Mapper<RemoteProduct, ProductModel>() {
    
         override fun map(t: RemoteProduct): ProductModel {
             // Pass any argument you want or do some business logic
             return ProductModel(t.id, t.name)
         }
    

    Now I Suggest injecting this ProductMapper inside the repo when you get the response from API or locale database then return mapped data to the use-case.

    But anyway you can inject this mapper inside use-case like this:

    class GetProductsUseCase @Inject constructor (private val productsMapper: ProductsMapper) {
    
       // Don't forget to inject your repo too
       operator fun invoke(): ProductMode {
           return productsMapper.map(repo.getProduct())
       }
    
    }
    

    Finally using Hilt create new module to bind ProductMapper in our case there is no need to do that step but if your mapper depends on another classes you need to add it in module like this:

    @Module
    @InstallIn(SingltonComponent::Class)
    interface AppModule {
       
      @Binds
      fun bindProductDetailsMapper(productsMapper: ProductsMapper): Mapper
    
    }