2017-10-19 6 views
0

私は理解しがたい奇妙な問題に遭遇しました。私はcallableからobservableを生成するいくつかのコードを書いています。それはうまくコンパイルされますが、スケジューラを指定するとすぐに戻り型が変更され、コンパイルされません。ここでsubscribeOn()を追加すると、観測可能な戻り値の型が変更されます

は(コンパイル)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()) 

コンパイル時のエラーメッセージ:

/** 
* 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とのコードです次のようになります。

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

確かに、スケジューラを指定すると、返される型は変更しないでください。何か案は?

+0

イムわからないが、あなたが観察するメソッドの戻り値を変更してみてくださいことができるように、私の最初に考えたのは、(ダガーなど)の継承の種類を理解していないRxKotlinこと(Kotlinに精通していない)ですか<? Collection を継承します。ここでも、Kotlinの構文に慣れていない提案があります。 – Inkognito

答えて

1

私はあなたが戻り値型との共分散を定義する必要が思う:out Tを使用して

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

は、Javaで? extends Tと同じです。

また、Collectionのみを使用することもできます。あなたの最初の例では、Observable.fromCallable()の戻り型はfunの戻り型によって推測されますが、2番目の例ではCallableの戻り型によって推測されます。だから、それを直接宣言:

Observable.fromCallable<Collections<Model.RoomBooking>> { ... } 
+0

これは正解です。 –

関連する問題