I want to return the data from the repository to the viewmodel without using any third-party
class MyRepository{
// Some code that return the data from webservice
}
class MyViewModel:ViewModel(){
init{
val repo= MyRepository()
MyRepository.getData()
}
//I need a way to operate on the data that I get from repository
}
ViewModel call -> Repoistory get the data-> ViewModel do operation on the data
With no third-parties library .. just the android studio SDK.
You can use callbacks to be notified when a work is done. The way to do it would be to pass the view model as a parameter to the method that will perform the work. I recommend you to define an interface so the repository does not rely directly on the view model but rather an interface.
The solution would look something like:
interface WebServiceCallback {
fun onWebServiceSuccess(data: MyObject)
fun onWebServiceError(error: MyError)
}
class MyViewModel: ViewModel(), WebServiceCallback {
init {
val repo = MyRepository()
repo.getData(this)
}
override fun onWebServiceSuccess(data: MyObject) {
//Implementation of what to do on success
}
override fun onWebServiceError(error: MyError) {
//Implementation of what to do on failure
}
}
class MyRepository {
fun getData(callback: WebServiceCallback) {
//Do your service call however you have implemented it
if(serviceResponse.isSuccess() == true) {
callback.onWebServiceSuccess(serviceResponse.data)
} else {
callback.onWebServiceError(serviceResponse.error)
}
}
}
This solution will call the respective methods on the view model after you have completed the work on the repo. Hope this answer it's helpful to you.