Skip to content

Instantly share code, notes, and snippets.

@Anrimian
Created October 9, 2017 11:59
Show Gist options
  • Save Anrimian/f82269b53c1c372e650580dd2cd20ddb to your computer and use it in GitHub Desktop.
Save Anrimian/f82269b53c1c372e650580dd2cd20ddb to your computer and use it in GitHub Desktop.
Simple RxJava2 wrapper for Android BroadcastReceiver

RxReceivers

Simple RxJava2 wrapper for Android BroadcastReceiver

How to use it:

RxReceivers.from("YOUR ACTION HERE", context)
    .subscribe(intent -> {    
        //do what you want here, but don't forget to unsubscribe
});
class BroadcastDisposable implements Disposable {
private BroadcastReceiver receiver;
private Context ctx;
private boolean isDisposed = false;
BroadcastDisposable(@NonNull BroadcastReceiver receiver, @NonNull Context ctx) {
this.receiver = receiver;
this.ctx = ctx;
}
@Override
public void dispose() {
if (!isDisposed) {
ctx.unregisterReceiver(receiver);
isDisposed = true;
}
}
@Override
public boolean isDisposed() {
return isDisposed;
}
}
public class RxReceivers {
public static Observable<Intent> from(@NonNull final String action, @NonNull final Context ctx) {
IntentFilter filter = new IntentFilter(action);
return from(filter, ctx);
}
public static Observable<Intent> from(@NonNull final IntentFilter intentFilter, @NonNull final Context ctx) {
return Observable.create(new ObservableOnSubscribe<Intent>() {
Context appContext = ctx.getApplicationContext();
@Override
public void subscribe(@NonNull final ObservableEmitter<Intent> emitter) throws Exception {
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
emitter.onNext(intent);
}
};
emitter.setDisposable(new BroadcastDisposable(receiver, appContext));
appContext.registerReceiver(receiver, intentFilter);
}
});
}
}
@Anrimian
Copy link
Author

Anrimian commented May 15, 2019

Just regular rx java way, subscribe() returns disposable, it is used for unsubscription.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment