Skip to content

Instantly share code, notes, and snippets.

@juliuscanute
Last active December 8, 2019 10:13
Show Gist options
  • Select an option

  • Save juliuscanute/2fbdf9cb814d24897f31a45bc923058c to your computer and use it in GitHub Desktop.

Select an option

Save juliuscanute/2fbdf9cb814d24897f31a45bc923058c to your computer and use it in GitHub Desktop.
[UI Layer] #clean #architecture #android
package com.raywenderlich.android.creatures.presentation.browse
open class BrowseCreaturesViewModel @Inject internal constructor(
private val getCreatures: GetCreatures,
private val creatureMapper: CreatureMapper) : ViewModel() {
private val creaturesLiveData: MutableLiveData<Resource<List<CreatureView>>> = MutableLiveData()
init {
fetchCreatures()
}
override fun onCleared() {
getCreatures.dispose()
super.onCleared()
}
fun getCreatures(): LiveData<Resource<List<CreatureView>>> {
return creaturesLiveData
}
fun fetchCreatures() {
creaturesLiveData.postValue(Resource(ResourceState.LOADING, null, null))
return getCreatures.execute(CreatureSubscriber())
}
inner class CreatureSubscriber: DisposableSubscriber<List<Creature>>() {
override fun onComplete() { }
override fun onNext(t: List<Creature>) {
creaturesLiveData.postValue(Resource(ResourceState.SUCCESS,
t.map { creatureMapper.mapToView(it) }, null))
}
override fun onError(exception: Throwable) {
creaturesLiveData.postValue(Resource(ResourceState.ERROR, null, exception.message))
}
}
}
package com.raywenderlich.android.creatures.presentation.mapper
open class CreatureMapper @Inject constructor(): Mapper<CreatureView, Creature> {
override fun mapToView(type: Creature) =
CreatureView(type.firstName, type.lastName, type.nickname, type.image, type.planet)
}
class MainActivity : AppCompatActivity() {
override fun onStart() {
super.onStart()
browseCreaturesViewModel.getCreatures().observe(this,
Observer<Resource<List<CreatureView>>> {
if (it != null) this.handleDataState(it.status, it.data, it.message) })
}
private fun handleDataState(resourceState: ResourceState, data: List<CreatureView>?,
message: String?) {
when (resourceState) {
ResourceState.LOADING -> setupScreenForLoadingState()
ResourceState.SUCCESS -> setupScreenForSuccess(data)
ResourceState.ERROR -> setupScreenForError(message)
}
}
}
package com.raywenderlich.android.creatures.presentation.mapper
interface Mapper<out V, in D> {
fun mapToView(type: D): V
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment