Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pratamawijaya/2931d0920b14962444d4733e70918623 to your computer and use it in GitHub Desktop.
Save pratamawijaya/2931d0920b14962444d4733e70918623 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