【问题标题】:Realm Asynchronous Transactions Order Structure in AndroidAndroid中的Realm异步事务顺序结构
【发布时间】:2017-06-19 07:23:23
【问题描述】:

我想按顺序执行以下方法。这意味着,如果 A 方法结束,则 B 开始。如果 B 结束 C 开始等等。

public void InitializeAPI {
    public static void init_A(Context mContext) {
        Realm.init(mContext);
        Realm realm = Realm.getDefaultInstance();
        realm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                // Some working is here.
            }
        }, new Realm.Transaction.OnSuccess() {
            // Some proceesing lines are here.
        }, new Realm.Transaction.OnError() {
            Log.d("AsyncTransaction", "ERROR");
        });
        // And there are lots of other TransactionAsync() line in this methods.
    }
    public static void init_B(Context mContext) {...}
    public static void init_C(Context mContext) {...}
    // and So many initialize methods.
}

如您所见,当我执行init_A(Context) 时,Async Transaction 将在后台运行。

但问题是init_B需要在init_A结束后执行。 init_C 也。我该如何设计这件事??

当然,我知道有Realm.Transaction.OnSuccess() 但是,如果我在Realm.Transaction.OnSuccess() init_Ainit_B,我认为代码不会整洁或对维护不好。

【问题讨论】:

    标签: java android android-asynctask transactions realm


    【解决方案1】:

    你为什么不使用这样的东西:

     realm.beginTransaction();
    
      //... add or update objects here ...
    
     realm.commitTransaction();
    

    而不是异步调用。 它将确保代码同步工作。

    希望对您有所帮助..!

    【讨论】:

    • (抱歉回复晚了)但是,你可以看到类名InitializeAPI,有很多HTTP请求和解析代码。如果不是Async,是不是性能低(低速)?
    • 有将近 600 个请求。
    • 尝试检查RealM lib中方法executeTransactionAsync的代码,你会看到他们使用的是相同的realm.beginTransaction();和领域.commitTransaction();是的,600 是一个巨大的数字,但首先检查 executeTransactionAsync 方法的代码。 (使用 ctrl+click)
    【解决方案2】:

    您可以通过OnSuccess 中的处理程序发送消息来触发init_B。但这看起来也好不到哪里去。因此,如果您想在不阻塞 UI 的情况下进行初始化,创建自己的线程可能是一个不错的选择。

    public void InitializeAPI {
        public static void init_A(Context mContext) {
            Realm.init(mContext);
            Realm realm = Realm.getDefaultInstance();
            realm.beginTransaction();
            // Write data
            realm.commitTransaction();
            realm.close();
        }
        public static void init_B(Context mContext) {...}
        public static void init_C(Context mContext) {...}
        // and So many initialize methods.
        public static void init() {
            init_A();
            init_B();
            init_C();
            //...
        }
    }
    
    Thread thread = new Thread(new Runnable() { 
        @Override
        public void run() {
            InitializeAPI.init();
            // Notify the main thread that initialization is done.
            handler.post(initialziedRunnable);
        }
    });
    thread.start();
    

    【讨论】:

    • 哦,其实我对Handler不熟悉,所以,我会多研究一下:) 研究完可以多加评论吗?
    猜你喜欢
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 2017-08-30
    相关资源
    最近更新 更多