Skip to content

Instantly share code, notes, and snippets.

@mtychyna
Last active March 22, 2018 09:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mtychyna/40b01e5291571c76909f842d5ca94da4 to your computer and use it in GitHub Desktop.
Save mtychyna/40b01e5291571c76909f842d5ca94da4 to your computer and use it in GitHub Desktop.
/* Copyright 2016 iMykolaPro
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
/**
* Example of usage:
* *** Was:
* public Observable<T> query(Class<T> clazz, String fieldName, long value) {
* return getRealmAsObservable(clazz)
* .flatMap(realm ->
* RealmObject.asObservable(
* realm.where(clazz)
* .equalTo(fieldName, value)
* .findFirstAsync()
* )
* .filter(RealmObject::isLoaded)
* .doOnUnsubscribe(realm::close));
* }
* *** Became:
* public Observable<T> query(Class<T> clazz, String fieldName, long value) {
* return getRealmAsObservable2(clazz)
* .flatMap(realm ->
* RealmObjectObservable.from(
* realm.where(clazz)
* .equalTo(fieldName, value)
* .findFirstAsync()
* )
* .filter(RealmObject::isLoaded)
* .doOnDispose(realm::close));
* }
*/
public class RealmObjectObservable<T extends RealmModel> implements
ObservableOnSubscribe<T> {
public static <T extends RealmModel> Observable<T> from(@NonNull T object) {
return Observable.create(new RealmObjectObservable<T>(object));
}
private final T object;
private RealmObjectObservable(@NonNull T object) {
this.object = object;
}
@Override
public void subscribe(ObservableEmitter<T> emitter) throws Exception {
// Initial element
emitter.onNext(object);
RealmChangeListener<T> changeListener = new RealmChangeListener<T>() {
@Override
public void onChange(T element) {
emitter.onNext(element);
}
};
RealmObject.addChangeListener(object, changeListener);
emitter.setCancellable(new Cancellable() {
@Override
public void cancel() throws Exception {
RealmObject.removeChangeListener(object, changeListener);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment