Last active
March 22, 2018 09:51
-
-
Save mtychyna/40b01e5291571c76909f842d5ca94da4 to your computer and use it in GitHub Desktop.
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
/* 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