【问题标题】:Use realm with promise in Android (Kotlin)在 Android (Kotlin) 中使用带 Promise 的领域
【发布时间】:2018-04-19 21:05:25
【问题描述】:

我尝试在 Android (Kotlin) 中使用带 promise 的领域库,但是当执行“resolve”方法时,返回的对象列表无效。

在下一个示例中,我创建了一个“findCountries”方法,该方法以异步模式查找国家/地区(实际上,如果适用,我会使用 promise 在我的领域数据库中同步,然后从我的领域数据库中进行查询)

fun findCountries(query: String? = null): Promise<Any?,Any?>{
val deferred = deferred<Any?,Any?>()
var result : List<TopupCountry> = ArrayList()
Realm.getDefaultInstance().executeTransactionAsync(Realm.Transaction { instance->
    result = instance.where(TopupCountry::class.java).findAll()
    deferred.resolve(result)
}, Realm.Transaction.OnSuccess {
    Log.i(ActTpListCountry.LOG_TAG,result.toString())
})
return deferred.promise}

在上面的例子中,如果领域类有数据,并且你在调用“resolve”方法之前得到了“result”参数的值,它会完美返回数据。但是,当您在解析回调中捕获结果时,它表示每个对象都是无效的。

See an error image example here

有什么建议吗?

【问题讨论】:

  • 你有 3 个问题:1.)你没有关闭 Realm 实例,永远 2.)你试图打开一个异步写入事务来读取,而不是仅仅使用 findAllAsync()和 3.) 你试图从一个不同的线程访问 RealmResults 而不是你从中检索它,所以它会给你非法状态异常
  • 阅读 the official documentationreferring to official example 可能会有所帮助。
  • 感谢您的回复。我认为问题与观察#3有关,我会检查官方示例,我会告诉你,再次感谢

标签: android promise kotlin realm


【解决方案1】:

我听从了@EpicPandaForce 的建议,找到了替代解决方案:

 /**
     * Method to find the countries
     */
    fun findCountries(query: String? = null, event: RealmEvent? = null){
        val realm = Realm.getDefaultInstance()
        val result = realm.where(TopupCountry::class.java).findAllAsync()
        result.addChangeListener(OrderedRealmCollectionChangeListener { realmResult, changeSet ->
            event?.onFindResult(realmResult)
            realm.close()
        })
    }

在这种情况下,我使用领域中的异步函数并应用更改侦听器方法。现在,我将使用接口而不是承诺

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多