1

我遇到了一个我很难理解的奇怪问题。我编写了一些从可调用对象创建可观察对象的代码。它编译得很好,但是一旦我为它指定了一个调度程序,它就会改变返回类型并且不会编译。

这是没有 subscribeOn 的代码(编译):

/**
 * Gets all the room bookings for the specified day
 */
override fun getRoomBookingsForDay(date: Date): Observable<Collection<Model.RoomBooking>> =
        Observable.fromCallable {
            Realm.getDefaultInstance().use { realm ->
                // Get all the bookings that begin and end within the specified date
                val dbRoomBookings =
                        realm.where(DBRoomBooking::class.java)
                                .greaterThan("timeFromUtc", date)
                                .lessThan("timeToUtc", date)
                                .findAllSorted("timeFromUtc")

                if (dbRoomBookings.isEmpty()) {
                    emptyList()
                } else {
                    dbRoomBookings.asSequence().map { dbRoomBooking ->
                        makeRoomBookingModel(dbRoomBooking)
                    }.filterNotNull().toList()
                }
            }
        }

这是带有 subscribeOn 的代码(无法编译):

/**
 * Gets all the room bookings for the specified day
 */
override fun getRoomBookingsForDay(date: Date): Observable<Collection<Model.RoomBooking>> =
        Observable.fromCallable {
            Realm.getDefaultInstance().use { realm ->
                // Get all the bookings that begin and end within the specified date
                val dbRoomBookings =
                        realm.where(DBRoomBooking::class.java)
                                .greaterThan("timeFromUtc", date)
                                .lessThan("timeToUtc", date)
                                .findAllSorted("timeFromUtc")

                if (dbRoomBookings.isEmpty()) {
                    emptyList()
                } else {
                    dbRoomBookings.asSequence().map { dbRoomBooking ->
                        makeRoomBookingModel(dbRoomBooking)
                    }.filterNotNull().toList()
                }
            }
        }.subscribeOn(AndroidRealmSchedulers.realmThread())

编译时错误消息是:

Type mismatch.
Required: Observable<Collection<Model.RoomBooking>>
Found: Observable<List<Model.RoomBooking>!>!

当然,指定调度程序不应该改变返回的类型?有任何想法吗?

4

1 回答 1

1

我认为您必须使用返回类型定义协方差:

override fun getRoomBookingsForDay(date: Date): Observable<out Collection<Model.RoomBooking>>

使用与在 Javaout T中相同。? extends T

或者,您可以确保仅使用Collection. 在您的第一个示例中,返回类型Observable.fromCallable()由 the 的返回类型推断,而在第二个示例中fun由 the 的返回类型推断。Callable所以直接声明:

Observable.fromCallable<Collections<Model.RoomBooking>> { ... }
于 2017-10-20T19:17:18.803 回答