I have an app based on MVVM architecture. I have two modules that repository and datasource. And using coroutines. I came across some projects on Github they applied different ways.

My implementation like this;

You can think naming as login, profile etc. instead of X letter

datasource interface

interface IXDatasource{
   suspend fun fetchData(): LiveData<XResponse>
}

datasource implementation

class XDatasourceImp  @Inject constructor(private val apiService: ApiService) : IXDatasource{
   suspend fun fetchData(): LiveData<XResponse> {
       // getting data
       return xResponse
   }
} 

repository interface

 interface XRepository {
    suspend fun getXData(): LiveData<XResponse>
 }

repository implementation

class XRepositoryImp @Inject constructor(private val iDatasource: IXDatasource): XRepository {
    override suspend fun getXData(): LiveData<XResponse> {
        return withContext(Dispatchers.IO) {
            iDatasource.fetchData()
        }
    }
}

I called this in my ViewModel

class XViewModel @Inject constructor(xRepository: XRepository) : BaseViewModel() {
    val xModel by lazyDeferred {
        xRepository.getXData()
    }
}

And I use in my activity/fragment

private fun init() = launch {
    val xModel = viewModel.xModel.await()
    xModel.observe([email protected], Observer {
        if (it == null) {
            [email protected]
        }
        // filling views or doing sth
   })
}

It works but I wonder all of them is required or not? I can apply the room database to my datasource. Is there any way better than this? I know it can change by the case of the app. I try to find the best way. I will be happy if you suggest anything or share anything about repository pattern implementation.

0 Answers