Say I have a Field
class with a harvest
function like this:
class Field {
func harvest(handler: (Vegetable) -> Void) {
…
handler(carrot)
…
handler(potato)
…
handler(carrot)
…
}
}
I also have a Reactive version/API for the same function:
import RxSwift
extension Reactive where Base: Field {
func harvest() -> Observable<Vegetable> {
return Observable.create { observer in
self.base.harvest(handler: observer.onNext)
return Disposables.create()
}
}
}
For testing purposes, I created a subclass of Field
named MockField
that overrides harvest(:)
to invoke the handler with a set of stubbed Vegetable
s. When using the MockField
object like field.harvest(:)
everything works fine and I get the stubbed vegetables.
Now I want to do the same with the Reactive extension to stub calls to field.rx.harvest
, but I cannot override it to return stubbed Vegetables! How can I override functions in the rx
namespace?
Probably the easiest way to do this would not be subclassing, but defining harvest() -> Observable<Vegetable>
in terms of Field.harvest(handler:)
import RxSwift
extension Reactive where Base: Field {
func harvest() -> Observable<Vegetable> {
return Observable.create { observer in
self.base.harvest(handler: observer.onNext)
return Disposables.create()
}
}
}
Doing it this way you will not need to maintain two implementations of harvest
.
PS: The block passed to a disposable should cancel the action, not send the completed event. If there is no facility to cancel harvest(handler:)
, you can simply return Disposables.create()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.