Last active
January 20, 2022 23:13
-
-
Save sambroad/7fbcc6b54cadd2224d5c58c3441826c8 to your computer and use it in GitHub Desktop.
An RxJava-friendly AlertDialog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.meetup.rx | |
import android.content.Context | |
import android.support.annotation.StringRes | |
import android.support.v7.app.AlertDialog | |
import rx.Emitter | |
import rx.Observable | |
/** | |
* | |
* A lightweight version of (and inspired by) https://github.com/xavierlepretre/rx-alert-dialog | |
* | |
* Usage: | |
* observable | |
* .observeOn(AndroidSchedulers.mainThread()) | |
* .flatMap({ event -> | |
* RxAlertDialog.show(context, R.string.title, R.string.message, android.R.string.ok) | |
* }) | |
* .subscribe({ button -> | |
* when (button) { | |
* RxAlertDialog.BUTTON_POSITIVE -> Log.v("OK") | |
* RxAlertDialog.BUTTON_NEGATIVE-> Log.v("Cancel") | |
* RxAlertDialog.DISMISS_ALERT-> Log.v("Dismissed") | |
* } | |
* }) | |
* | |
*/ | |
class RxAlertDialog { | |
companion object { | |
const val DISMISS_ALERT = 0 | |
const val BUTTON_POSITIVE = 1 | |
const val BUTTON_NEGATIVE = 2 | |
@JvmStatic @JvmOverloads | |
fun show( | |
context: Context, | |
@StringRes title: Int? = null, | |
@StringRes message: Int? = null, | |
@StringRes positiveButton: Int? = null, | |
@StringRes negativeButton: Int? = null): Observable<Int> { | |
return Observable.create<Int>({ emitter -> | |
val builder = AlertDialog.Builder(context) | |
.setOnDismissListener { emitter.onNext(DISMISS_ALERT) } | |
title?.let { builder.setTitle(it)} | |
message?.let { builder.setMessage(it)} | |
positiveButton?.let { builder.setPositiveButton(positiveButton, { _, _ -> emitter.onNext(BUTTON_POSITIVE)})} | |
negativeButton?.let { builder.setNegativeButton(negativeButton, { _, _ -> emitter.onNext(BUTTON_NEGATIVE)})} | |
val dialog = builder.show() | |
emitter.setCancellation { dialog.dismiss() } | |
}, Emitter.BackpressureMode.NONE) | |
} | |
} | |
} |
This looks like it's in RX 1.x. Emitter is different now. http://reactivex.io/RxJava/javadoc/io/reactivex/Emitter.html
You could use Single instead of Observable btw
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It seems that you have forgotten to add the
import rx.Emitter
import rx.Observable
Are they your own overridden versions of these?
Thanks in advance