Last active
October 31, 2019 15:44
-
-
Save kyhule/4075c832cab4148a353a02c95dd9c0e9 to your computer and use it in GitHub Desktop.
Reactive Android System callbacks #android #rxjava
This file contains hidden or 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
Observable.create<Boolean> { emitter -> | |
val listener = AccessibilityStateChangeListener { enabled -> | |
if (emitter.isDisposed) return@AccessibilityStateChangeListener | |
emitter.onNext(enabled) | |
} | |
accessibilityManager.addAccessibilityStateChangeListener(listener) | |
emitter.setCancellable { | |
accessibilityManager.removeAccessibilityStateChangeListener(listener) | |
} | |
} |
This file contains hidden or 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
object WifiManagerObservable { | |
/** | |
* Observes the WiFi network the device is connected to. | |
* Returns the current WiFi network information as a [WifiInfo] object. | |
* | |
* @param context Context of the activity or an application | |
* @return RxJava Observable with WifiInfo | |
*/ | |
@RequiresPermission(ACCESS_WIFI_STATE) | |
fun observeWifiAccessPointChanges(context: Context): Observable<WifiInfo> { | |
val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager | |
val filter = IntentFilter() | |
filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION) | |
return Observable.create(object : ObservableOnSubscribe<WifiInfo>() { | |
@Throws(Exception::class) | |
fun subscribe(emitter: ObservableEmitter<WifiInfo>) { | |
val receiver = createAccessPointChangesReceiver(emitter, wifiManager) | |
context.registerReceiver(receiver, filter) | |
val disposable = disposeInUiThread(object : Action() { | |
fun run() { | |
tryToUnregisterReceiver(context, receiver) | |
} | |
}) | |
emitter.setDisposable(disposable) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment