[ionic4] - how to use hardware back button to close loading (when pressed during loading) or to go to previous page or to exit the app

How to use hardware back button to close loading (when it is pressed during loading) or to go to previous page (when the page is not selected from menu) or to exit the app (if the page is selected from menu)…

I was implemented above functionality in ionic 3 (as shown below) how to achieve the same in ionic 4?

constructor(private ionicApp: IonApp) { 

}

this.platform.backButton.subscribe(async () => {	
                let activePortal = this.ionicApp.getActive() || this.ionicApp._modalPortal.getActive() || this.ionicApp._overlayPortal.getActive();
                if (activePortal) {
                    activePortal.dismiss();
                }
                else if (this.nav.canGoBack()) {
                    this.nav.pop();
                } else {
                    let confirm = await this.alertCtrl.create({
                        header: 'Confirm',
                        message: 'Do you want to exit ?',
                        buttons: [
                            {
                                text: 'Cancel', handler: () => { }
                            },
                            {
                                text: 'Ok',
                                handler: () => {
                                    this.platform.exitApp();
                                }
                            }
                        ]
                    });
                    await confirm.present();
                }
            });

@lucasbasquerotto

@pantarmj Maybe this can help you (I haven’t implemented it myself):