Skip to content

Instantly share code, notes, and snippets.

@hleinone
Created February 6, 2019 09:09
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 hleinone/0a9720013b13ab20b5a901ccc8bee01a to your computer and use it in GitHub Desktop.
Save hleinone/0a9720013b13ab20b5a901ccc8bee01a to your computer and use it in GitHub Desktop.
Android AlertDialog Rx extension
import android.content.DialogInterface
import androidx.appcompat.app.AlertDialog
import com.jakewharton.rxbinding2.view.clicks
import io.reactivex.Maybe
import io.reactivex.Single
/**
* Sets the dialog non-cancelable. Emits either {@link DialogInterface#BUTTON_POSITIVE},
* {@link DialogInterface#BUTTON_NEGATIVE} or {@link DialogInterface#BUTTON_NEUTRAL} and dismisses
* the dialog.
*/
@androidx.annotation.CheckResult
fun AlertDialog.clicks(): Single<Int> {
setCancelable(false)
return Maybe.merge(
getButton(DialogInterface.BUTTON_POSITIVE).clicks().firstElement().map { DialogInterface.BUTTON_POSITIVE },
getButton(DialogInterface.BUTTON_NEGATIVE).clicks().firstElement().map { DialogInterface.BUTTON_NEGATIVE },
getButton(DialogInterface.BUTTON_NEUTRAL).clicks().firstElement().map { DialogInterface.BUTTON_NEUTRAL })
.firstOrError()
.doOnSuccess {
dismiss()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment