请选择 进入手机版 | 继续访问电脑版
  • 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

android - Realm 自行关闭

[复制链接]
菜鸟教程小白 发表于 2022-11-6 16:17:05 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我在 Application 对象上使用一个静态全局 Realm 实例(从不关闭),仅用于 UI 线程,

@UiThread
public static Realm getRealm() {
    if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
        return realmInstance;
    } else {
        Timber.e("Illegal access to getRealmObservable");
        throw new IllegalStateException("Only UI Thread can access this realm");
    }
}

以及 WorkerThread 的另一个单一用途 Realm 如下:

@WorkerThread
public static void executeOnSingleUseRealm(final Realm.Transaction transaction) {
    if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
        Timber.e("Wrong thread for Realm");
        throw new IllegalStateException("Wrong thread for Single use Realm");
    }

    Realm realm = null;
    try {
        realm = Realm.getDefaultInstance();
        realm.executeTransaction(transaction);
    } catch (Exception e) {
        Timber.e(e, "Exception in Single Use Realm transaction");
        throw e;
    } finally {
        if (realm != null) {
            realm.close();
        }
    }
}

但是我仍然看到使用单个全局 Realm 实例时崩溃:此 Realm 实例已经关闭,使其无法使用。

我什至不知道这怎么可能。

这是我初始化 Realm 实例的方法:

应用程序创建

void onCreate(){
    ....
        Observable
            .fromCallable(() -> {
                Realm.init(SVApplication.this);
                RealmConfiguration realmConfiguration = new RealmConfiguration.Builder()
                        .deleteRealmIfMigrationNeeded()
                        .build();
                Realm.compactRealm(realmConfiguration);
                Realm.setDefaultConfiguration(realmConfiguration);
                return true;
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe((v) -> onRealmLoaded());
    }
}

void onRealmLoaded(){
    realmInstance = Realm.getDefaultInstance();
    ....
}

这是其中一项 Activity 的崩溃之一:

void onStart(){
    ....    subscribeUntilDetach(realmInstance.where(Notification.class).findAllAsync().asObservable()
                        .onBackpressureLatest()
                        .switchIfEmpty(emptyNotification())
                        .map(notifications -> notifications.where().isNull("readTime").or().isEmpty("readTime").count())
                        .onBackpressureLatest()
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(count -> {
                            if (count == 0L) {
                                mNotificationBadge.setVisibility(View.GONE);
                            } else {
                                mNotificationBadge.setText(String.format(Locale.getDefault(), "%d", count));
                                mNotificationBadge.setVisibility(View.VISIBLE);
                            }
                        }, throwable -> Timber.e(throwable, "Error setting notification count")));
}

@Override
protected void onPause() {
    super.onPause();
    if (isFinishing()) {
        mCompositeSubscription.clear();
    }
}

protected void subscribeUntilDetach(@NonNull Subscription subscription) {
    mCompositeSubscription.add(subscription);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (mCompositeSubscription.hasSubscriptions()) {
        mCompositeSubscription.unsubscribe();
    }
}

在某些 Activity 中,此行也会因相同的错误而崩溃:

mCompositeSubscription.unsubscribe();

这是来自 Crashlytics 的堆栈跟踪,可能并不完全准确。

Fatal Exception: java.lang.RuntimeException: Unable to resume activity {com.myapp.mobile/com.teknoloji.myapp.ui.pages.HomeActivity}: rx.b.f: This Realm instance has already been closed, making it unusable.
   at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3353)
   at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3384)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1443)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:168)
   at android.app.ActivityThread.main(ActivityThread.java:5885)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by rx.b.f: This Realm instance has already been closed, making it unusable.
   at rx.internal.util.InternalObservableUtils$ErrorNotImplementedAction.call(Unknown Source)
   at rx.internal.util.InternalObservableUtils$ErrorNotImplementedAction.call(Unknown Source)
   at rx.internal.util.ActionSubscriber.onError(Unknown Source)
   at rx.observers.SafeSubscriber._onError(Unknown Source)
   at rx.observers.SafeSubscriber.onError(Unknown Source)
   at rx.exceptions.Exceptions.propagate(Unknown Source)
   at rx.observers.SafeSubscriber.onNext(Unknown Source)
   at rx.internal.producers.SingleProducer.request(Unknown Source)
   at rx.Subscriber.setProducer(Unknown Source)
   at rx.Subscriber.setProducer(Unknown Source)
   at rx.internal.operators.OperatorSingle$ParentSubscriber.onCompleted(Unknown Source)
   at rx.internal.operators.OperatorTake$1.onNext(Unknown Source)
   at rx.internal.operators.NotificationLite.next(Unknown Source)
   at rx.subjects.SubjectSubscriptionManager$SubjectObserver.accept(Unknown Source)
   at rx.subjects.SubjectSubscriptionManager$SubjectObserver.emitNext(Unknown Source)
   at rx.subjects.SubjectSubscriptionManager$SubjectObserver.emitFirst(Unknown Source)
   at rx.subjects.BehaviorSubject$1.call(Unknown Source)
   at rx.subjects.BehaviorSubject$1.call(Unknown Source)
   at rx.subjects.SubjectSubscriptionManager.call(Unknown Source)
   at rx.subjects.SubjectSubscriptionManager.call(Unknown Source)
   at rx.subjects.SubjectSubscriptionManager.call(Unknown Source)
   at rx.internal.operators.OnSubscribeLift.call(Unknown Source)
   at rx.internal.operators.OnSubscribeLift.call(Unknown Source)
   at rx.internal.operators.OnSubscribeLift.call(Unknown Source)
   at rx.internal.operators.OnSubscribeLift.call(Unknown Source)
   at rx.Observable.create(Unknown Source)
   at rx.Observable.unsafeCreate(Unknown Source)
   at rx.Observable.create(Unknown Source)
   at com.teknoloji.myapp.ui.pages.HomeActivity.onStart(Unknown Source)
   at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1288)
   at android.app.Activity.performStart(Activity.java:6279)
   at android.app.Activity.performRestart(Activity.java:6325)
   at android.app.Activity.performResume(Activity.java:6330)
   at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3336)
   at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3384)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1443)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:168)
   at android.app.ActivityThread.main(ActivityThread.java:5885)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by java.lang.IllegalStateException: This Realm instance has already been closed, making it unusable.
   at io.realm.BaseRealm.checkIfValid(Unknown Source)
   at io.realm.Realm.init(Unknown Source)
   at com.teknoloji.myapp.ui.pages.HomeActivity.lambda$onStart$3(Unknown Source)
   at com.teknoloji.myapp.ui.pages.HomeActivity$$Lambda$1.call(Unknown Source)
   at rx.internal.util.ActionSubscriber.onNext(Unknown Source)
   at rx.observers.SafeSubscriber.onNext(Unknown Source)
   at rx.internal.producers.SingleProducer.request(Unknown Source)
   at rx.Subscriber.setProducer(Unknown Source)
   at rx.Subscriber.setProducer(Unknown Source)
   at rx.internal.operators.OperatorSingle$ParentSubscriber.onCompleted(Unknown Source)
   at rx.internal.operators.OperatorTake$1.onNext(Unknown Source)
   at rx.internal.operators.NotificationLite.next(Unknown Source)
   at rx.subjects.SubjectSubscriptionManager$SubjectObserver.accept(Unknown Source)
   at rx.subjects.SubjectSubscriptionManager$SubjectObserver.emitNext(Unknown Source)
   at rx.subjects.SubjectSubscriptionManager$SubjectObserver.emitFirst(Unknown Source)
   at rx.subjects.BehaviorSubject$1.call(Unknown Source)
   at rx.subjects.BehaviorSubject$1.call(Unknown Source)
   at rx.subjects.SubjectSubscriptionManager.call(Unknown Source)
   at rx.subjects.SubjectSubscriptionManager.call(Unknown Source)
   at rx.subjects.SubjectSubscriptionManager.call(Unknown Source)
   at rx.internal.operators.OnSubscribeLift.call(Unknown Source)
   at rx.internal.operators.OnSubscribeLift.call(Unknown Source)
   at rx.internal.operators.OnSubscribeLift.call(Unknown Source)
   at rx.internal.operators.OnSubscribeLift.call(Unknown Source)
   at rx.Observable.create(Unknown Source)
   at rx.Observable.unsafeCreate(Unknown Source)
   at rx.Observable.create(Unknown Source)
   at com.teknoloji.myapp.ui.pages.HomeActivity.onStart(Unknown Source)
   at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1288)
   at android.app.Activity.performStart(Activity.java:6279)
   at android.app.Activity.performRestart(Activity.java:6325)
   at android.app.Activity.performResume(Activity.java:6330)
   at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3336)
   at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3384)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1443)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:168)
   at android.app.ActivityThread.main(ActivityThread.java:5885)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)



Best Answer-推荐答案


问题是:

A closed exception indicates that you're attempting to use a closed realm, utilizing Realm in a way that would not be promoted as the best practice. ... Each activity is supposed to have its own realm instance for best performance. ... create a realm instance at onCreate() and destroy the instance at onDestory(). https://github.com/realm/realm-java/issues/2594#issuecomment-211793848

还有

...it is not a good idea that keep a static field of Realm in the class. It is recommended to control the Realm's life cycle within the Activity/Fragment/etc https://realm.io/docs/java/latest/#controlling-the-lifecycle-of-realm-instances

因为在 Realm 中创建新实例,当至少有一个打开时,速度非常快,不要害怕创建多个 Realm 实例。

Realm 的一位高级软件工程师指出 here :

As long as you have at least one instance open on a thread calling Realm.getInstance() it is just a HashMap lookup... Best practise is to keep the Realm instance open for as long as your thread lives.

Realm documentation 中描述了最佳实践。 :

// Setup Realm in your Application
public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this);
        RealmConfiguration realmConfiguration = new RealmConfiguration.Builder().build();
        Realm.setDefaultConfiguration(realmConfiguration);
    }
}

// onCreate()/onDestroy() overlap when switching between activities.
// Activity2.onCreate() will be called before Activity1.onDestroy()
// so the call to getDefaultInstance in Activity2 will be fast.
public class MyActivity extends Activity {
    private Realm realm;
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        realm = Realm.getDefaultInstance();
        // ...
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realm.close();
    }
}

对于工作线程,documentation recommends在开始时获取一个新的 Realm 实例并在结束时关闭它。

protected Void doInBackground(Void... params) {
    Realm realm = Realm.getDefaultInstance();
    try {
        // ... Use the Realm instance ...
    } finally {
        realm.close();
    }

    return null;
}

关于android - Realm 自行关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43619625/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝0

帖子790513

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap