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/accc0cf4e19c16405f7cb1d3107f10e8 to your computer and use it in GitHub Desktop.

Select an option

Save douglasiacovelli/accc0cf4e19c16405f7cb1d3107f10e8 to your computer and use it in GitHub Desktop.
fun onClickLikeButton() {
if (viewModel.liked) {
removeLike()
} else {
addLike()
}
}
private fun addLike() {
//First we update the local model so the user feels the action is instantaneous
viewModel.liked = true
viewModel.count++
//Then we call the API to update it on the server
apiService.addLike.enqueue({ response ->
//If everything goes right, we update the model with the information from the server
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.liked = false
viewModel.count--
})
}
private removeLike() {
//First we update the local model so the user feels the action is instantaneous
viewModel.liked = false
viewModel.count--
//Then we call the API to update it on the server
apiService.removeLike.enqueue({ response ->
//If everything goes right, we update the model with the information from the server
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.liked = true
viewModel.count++
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment