我遇到了一个我很难理解的奇怪问题。我编写了一些代码来创建一个可调用的observable。它编译得很好,但是一旦我为它指定了一个调度程序,它就会改变返回类型并且不会编译。
这是没有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>!>!
当然,指定调度程序不应该更改正在返回的类型?有什么想法吗?
答案 0 :(得分:1)
我认为您必须使用return-type定义协方差:
override fun getRoomBookingsForDay(date: Date): Observable<out Collection<Model.RoomBooking>>
使用out T
与Java中的? extends T
相同。
或者,您可以确保仅使用Collection
。在您的第一个示例中,Observable.fromCallable()
的返回类型由fun
的返回类型推断,而第二个示例中的Callable
的返回类型推断出Observable.fromCallable<Collections<Model.RoomBooking>> { ... }
的返回类型。所以直接申报:
bundle.putString("Types", types.toString());