Skip to content

Instantly share code, notes, and snippets.

@douglasiacovelli
Last active February 25, 2018 15:05
Show Gist options
  • Select an option

  • Save douglasiacovelli/7cac735e1d551a0ccc8394dc1e918127 to your computer and use it in GitHub Desktop.

Select an option

Save douglasiacovelli/7cac735e1d551a0ccc8394dc1e918127 to your computer and use it in GitHub Desktop.
class ViewModel {
//... here comes the attributes and the model
//we are changing (irrelevant for the example)
fun addLikeLocally() {
liked = true
count++
}
fun removeLikeLocally() {
liked = false
count--
}
}
//this is our class
fun onClickLikeButton() {
if (viewModel.liked) {
removeLike()
} else {
addLike()
}
}
private fun addLike() {
viewModel.addLikeLocally()
//Then we call the API to update it on the server
apiService.addLike.enqueue({ response ->
viewModel.count = response.count
}, { failure ->
//If any error occurs we should let the user know and go back to the previous state
Toast.makeToast(activity, "Ops, an error occurred", LENGTH_LONG).show()
viewModel.removeLikeLocally()
})
}
private removeLike() {
viewModel.removeLikeLocally()
//Then we call the API to update it on the server
apiService.removeLike.enqueue({ response ->
viewModel.count = response.count
}, { failure ->
//If any error occurs we should let the user know
Toast.makeToast(activity, "Ops, an error occurred", LENGTH_LONG).show()
viewModel.addLikeLocally()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment