I have several pages (Activities, Fragments) that list some posts. To receive these posts, I request them via Retrofit. To receive fresh posts, I call a method that requests them from the server whenever I open a new page.
Help me find best practices or solutions like pattern or architecture.
This is my pseudo code:
Activity
class Activity {
fun onCreate () {
viewModel.data.observe { state->
loader.isVisible = state is State.Loading
when(state) {
State.Data -> adapter.submitList(state.data)
State.Error -> showError(state.error)
}
}
}
}
ViewModel
class ViewModel(val loader: PostsLoader) {
val data get = loader.data.also {
loader.execute()
}
}
Loader (it is singleton?)
class PostsLoader(val repository: PostRepository) {
val data get(): LiveData<DataWrapper<List<Post>> = _data
private val _data = MutableLiveData<DataWrapper<List<Post>>()
fun execute() {
if (_data.value == null || _data.value == DataWrapper.Loading) return
_data.value = DataWrapper.Loading
try {
_data.value = DataWrapper.Success(repository.getPosts())
} catch(error: Throwable) {
_data.value = DataWrapper.Error(error)
}
}
}
Repository
class PostRepository(val api: Api) {
fun getPosts(): List<Post> {
return api.getPosts()
}
}
Aucun commentaire:
Enregistrer un commentaire