Trong các dự án Android của tôi, tôi sử dụng realm làm công cụ lưu trữ dữ liệu của mình. Tôi thích nó!
Tôi cũng sử dụng RxJava bởi vì nó làm cho "luồng" dễ dàng hơn nhiều, và tôi thực sự thích toàn bộ "suy nghĩ phản ứng". Tôi thích nó!
Lĩnh vực, RxJava, asObservable() và doOnUnsubscribe()
Tôi sử dụng mẫu MVP + một số ý tưởng "Kiến trúc sạch" để xây dựng ứng dụng của mình.
My Interactors
là những người duy nhất biết về Realm
. Tôi phơi bày dữ liệu với sự giúp đỡ của quan sát được, như thế này:
@Override
public Observable<City> getHomeTown() {
final Realm realm = Realm.getDefaultInstance();
return realm.where(City.class).equalTo("name", "Cluj-Napoca").findAllAsync().asObservable()
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
realm.close();
}
})
.compose(new NullIfNoRealmObject<City>());
}
Vấn đề là doOnUnsubscribe
tác dụng phụ của tôi được gọi trước khi Realm
có thể làm điều này, xử lý tiếp xúc quan sát:
Caused by: java.lang.IllegalStateException: This Realm instance has already been closed, making it unusable.
at io.realm.BaseRealm.checkIfValid(BaseRealm.java:344)
at io.realm.RealmResults.removeChangeListener(RealmResults.java:818)
at io.realm.rx.RealmObservableFactory$3$2.call(RealmObservableFactory.java:137)
at rx.subscriptions.BooleanSubscription.unsubscribe(BooleanSubscription.java:71)
at rx.internal.util.SubscriptionList.unsubscribeFromAll(SubscriptionList.java:124)
at rx.internal.util.SubscriptionList.unsubscribe(SubscriptionList.java:113)
at rx.Subscriber.unsubscribe(Subscriber.java:98)
at rx.internal.util.SubscriptionList.unsubscribeFromAll(SubscriptionList.java:124)
at rx.internal.util.SubscriptionList.unsubscribe(SubscriptionList.java:113)
at rx.Subscriber.unsubscribe(Subscriber.java:98)
at rx.subscriptions.CompositeSubscription.unsubscribeFromAll(CompositeSubscription.java:150)
at rx.subscriptions.CompositeSubscription.unsubscribe(CompositeSubscription.java:139)
at ro.tudorluca.realm.sandbox.city.CityPresenter.onDestroy(CityPresenter.java:62)
at ro.tudorluca.realm.sandbox.city.CityActivity.onDestroy(CityActivity.java:35)
tôi đã tạo một dự án sandbox cho trường hợp sử dụng này.
Tôi thực sự thích sử dụng Realm + RxJava, nhưng tôi dường như không thể tìm thấy một giải pháp sạch để close
sơ thẩm Realm khi tôi unsubscribe
(Tôi thường bỏ đăng ký khi hoạt động bị phá hủy). Bất kỳ ý tưởng?
Sửa 1: https://github.com/realm/realm-java/issues/2357
Chỉnh sửa 2: nhờ vào đội ngũ lãnh vực rất tích cực, đã có một pull request để khắc phục vấn đề này.
Hãy xem xét gói Realm bằng cách sử dụng Observable # bằng cách sử dụng, điều này sẽ đơn giản hóa phương thức getManagedRealm() của bạn: http://pastebin.com/CrzryvCq –
Tôi thử giải pháp của bạn và tôi gặp sự cố: quá nhiều tệp mở trong lĩnh vực –