简体   繁体   English

如何实施收房查询

[英]How to implement a RX room query

I'm quite new to Room and RXJava and I want to use them to perform a quite simple query but I have problem implementing the RX part and handle results. 我是RoomRXJava ,我想用它们执行一个非常简单的查询,但是在实现RX部分和处理结果时遇到问题。

@Dao
interface DepartmentDao{
//....
@Query ("SELECT employeesIds FROM Department WHERE Department_name LIKE :name")
 fun getEmployeesIds(name:String):String //this is a jsonArray stored as string
}

Then I have Kotlin object where I write some other methods related to the database others than ones from @Dao 然后我有Kotlin对象,在这里我写了一些其他与数据库有关的方法,而不是@Dao

object DBManager {
  fun getEmployeesIdsJsonArray():Completable = Completable.fromCallable {
        mDataBase.DepartmentDao().getEmployeesIds(deptName)
    }
}

I want to query this in my Fragment and use the query result (a string in this case) when the query completes. 我想在我的Fragment中查询它,并在查询完成时使用查询结果(在这种情况下为字符串)。 This is where I get locked and need your help. 这是我被锁定并需要您帮助的地方。

DBManager.getEmployeesIdsJsonArray()
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe( //here I get locked, how can I handle this?)

I expect to have something like 我希望有类似的东西

{
  onSuccess -> jsonString , //this is the string resulted, feel free to use it
  onError -> Log.e(TAG, "query failed")
}

but I'm not able to implement it successfully without all kind of errors regarding type expectations. 但是如果没有关于类型期望的所有错误,我将无法成功实现它。

I think the syntax you're looking for is this: 我认为您要寻找的语法是这样的:

  DBManager.getEmployeesIdsJsonArray()
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe( { jsonString ->
           // onNext
           // Do something with jsonString
        }, { throwable ->
           // onError
           // Do somethign with throwable
        } )

Well. 好。 Completable returns nothing, just termination event onComplete/onError Completable不返回任何内容,只是终止事件onComplete / onError

Try : 尝试:

  • Return Single in your Dao 在您的道中归还单身
  • Your subscribe method should looks like subscribe({function1},{function2}) 您的订阅方法应类似于subscription({function1},{function2})

And never use Schedulers.newThread() for IO operations. 绝对不要将Schedulers.newThread()用于IO操作。 Instead this prefer Schedulers.io(), because it use reusable threads from thread pool, while Schedulers.newThread() create just a new thread, which is not reusable 相反,它更喜欢Schedulers.io(),因为它使用线程池中的可重用线程,而Schedulers.newThread()只是创建一个新线程,不可重用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM