Last active
February 9, 2018 04:42
-
-
Save gmazzo/30ec4f15012a1d9025fdf068f1bdfe8c to your computer and use it in GitHub Desktop.
A util class for RxJava which provides Observable sources for Cursor, LocalBroadcastManager and SparseArray
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
import android.content.BroadcastReceiver; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.content.IntentFilter; | |
import android.database.Cursor; | |
import android.support.v4.content.LocalBroadcastManager; | |
import android.support.v4.util.LongSparseArray; | |
import android.util.SparseArray; | |
import io.reactivex.Observable; | |
import io.reactivex.functions.Function; | |
public final class RxUtils { | |
public static <T> Observable<T> fromCursor(Cursor cursor, Function<Cursor, T> parser) { | |
return Observable.create($ -> { | |
try { | |
while (!$.isDisposed() && cursor.moveToNext()) { | |
T value = parser.apply(cursor); | |
if (value != null) { | |
$.onNext(value); | |
} | |
} | |
$.onComplete(); | |
} finally { | |
cursor.close(); | |
} | |
}); | |
} | |
public static Observable<Intent> fromLocalBroadcast(Context context, String action, String... others) { | |
IntentFilter filter = new IntentFilter(action); | |
for (String other : others) { | |
filter.addAction(other); | |
} | |
return fromLocalBroadcast(context, filter); | |
} | |
public static Observable<Intent> fromLocalBroadcast(Context context, IntentFilter filter) { | |
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(context); | |
return Observable.create($ -> { | |
BroadcastReceiver receiver = new BroadcastReceiver() { | |
@Override | |
public void onReceive(Context context, Intent intent) { | |
$.onNext(intent); | |
} | |
}; | |
$.setCancellable(() -> manager.unregisterReceiver(receiver)); | |
manager.registerReceiver(receiver, filter); | |
}); | |
} | |
public static <T> Observable<T> fromSparse(SparseArray<T> array) { | |
return Observable.create($ -> { | |
for (int i = 0, c = array.size(); i < c; i++) { | |
$.onNext(array.valueAt(i)); | |
} | |
$.onComplete(); | |
}); | |
} | |
public static <T> Observable<T> fromSparse(LongSparseArray<T> array) { | |
return Observable.create($ -> { | |
for (int i = 0, c = array.size(); i < c; i++) { | |
$.onNext(array.valueAt(i)); | |
} | |
$.onComplete(); | |
}); | |
} | |
private RxUtils() { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment