Dimitar Dihanov
1 min readAug 13, 2019

--

Heads up to everyone, if you have a repository class that returns LiveData and you want to use the Event wrapper class, you don’t need to make the repository return LiveData<Event<Example>> you can simply do it in the ViewModel with Transformations.map for example:

Repository class has a method(you don’t need the Event wrapper here)

fun doSomething(value: Value): LiveData<Response> {
//an example task that does a network request and returns LiveData
val doSomethingTask = DoSomethingTask(value)
return doSomethingTask.data //this is LiveData<Response>
}

no need to use to use the Event class in the DoSomethingTask as we will wrap it later in the ViewModel

ViewModel:

fun doSomething(value: Value): LiveData<Event<Response>> = Transformations.map(repository.doSomething(value) { data -> Event(data)}

So just apply a map function to wrap the data in the Event class

Fragment:

viewModel.doSomething(value).observe(viewLifecycleOwner, Observer<Event<Response>> { data ->
data?.let {
//do your stuff
}
}
)

--

--

No responses yet