Skip to content

Instantly share code, notes, and snippets.

@abhaysood
Last active March 18, 2018 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhaysood/84da2a300bed145ec3e83b8612f40858 to your computer and use it in GitHub Desktop.
Save abhaysood/84da2a300bed145ec3e83b8612f40858 to your computer and use it in GitHub Desktop.
A simple component which is created when user clicks the cancel order button in the app. It is responsible for showing a confirmation dialog and actually cancelling the order by making an API call.
class OrderCancellationComponent(private val context: Context,
private val api: Api,
private val orderNumber: String) {
interface Callbacks {
fun onOrderCancelledSuccessfully()
fun onOrderCancellationFailed()
}
var callbacks: Callbacks? = null // Callbacks for communication with the parent component
private val cancelOrderDialog: DialogCard // A wrapper over bottom sheet dialog
init {
// Each component can attach a container view in the Activity.
// This behaviour is abstracted by the DialogCard.
// All a component needs to do is inflate a view to show in the dialog.
val contentView = LayoutInflater.from(context).inflate(R.layout.dialog_cancel_order, null)
cancelOrderDialog = DialogCard(context, contentView)
val cancelButton = contentView.findViewById<Button>(R.id.btn_cancel)
cancelButton.setOnClickListener {
cancelOrder()
}
}
// Shows the confirmation dialog when invoked by the parent.
fun showConfirmationDialog() {
cancelOrderDialog.show()
}
// Dimsisses the dialog when back is pressed.
fun onBackPress() {
dismiss()
}
// Dismisses the dialog
private fun dismiss() {
cancelOrderDialog.dismiss()
}
// Makes an API call to acually cancel the order.
private fun cancelOrder() {
subscription = api.cancelOrder(...)
.subscribe({
override fun onSuccess(...) {
dismiss()
callbacks?.onOrderCancelled()
}
override fun onError(e: Throwable) {
Toast.makeText(activity, "Could not cancel order", Toast.LENGTH_LONG).show()
callbacks?.onOrderCancelAPIFailed()
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment