Looking at some RxSwift test code, I knew it could be better. As I shared with Krunoslav Zaher aka kzaher in the RxSwift Slack community:
I feel the opportunity for improvement down to my soul.
Test Code
He kindly helped me simplify some RxSwift test code. He suggested that instead of:
1 2 3 |
oldBakeryServiceSpy.responseClosure = { observer in observer.onNext(Cake(cakeIdentification:"", html:"Some HTML")) } |
Do something like this:
1 2 3 |
oldBakeryServiceSpy.responseClosure = { just(Cake(cakeIdentification:"", html:"Some HTML")) } |
To make that work, I had to change the oldBakeryServiceSpy from something like this:
1 2 3 4 5 6 7 8 9 10 11 12 |
class OldBakeryServiceSpy: OldBakeryService { var responseClosure: ((AnyObserver<Cake>) -> Void)? override func makeRequest(cakeIdentification: String) -> Observable<Cake> { return create { observer in if let responseClosure = self.responseClosure { responseClosure(observer) } return NopDisposable.instance } } } |
To this:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class OldBakeryServiceSpy: OldBakeryService { var responseClosure: (() -> Observable<Cake>)? override func makeRequest(cakeIdentification: String) -> Observable<Cake> { guard let myClosure = responseClosure else { return just(Cake(cakeIdentification: "", html: "")) } return myClosure() } } |
This also allowed us to use failWith. As in:
1 2 3 |
oldBakeryServiceSpy.responseClosure = { failWith(OldBakeryError(message:"something", code: "999")) } |
More kzaher Words of Wisdom
if you are mocking, just use
just
,sequenceOf
,[].toObservable()
It was also shared that TestScheduler will be released soon and one can look at the unit tests.
What about Simplifying Our Use of the DisposeBag?
As a result of what we read in the README, we use DisposeBag objects often. As kzaher shared:
If you use operators, that will reduce the amount of dispose bags significantly. We handle all of disposing for you. You only dispose terminal endpoints where you do “subscribe”
All Part of the Game of Learning
Slowly things are improving. Although it’s all part of the game of learning something new, I think it would serve all well if someone created a game called “Simplify This RxSwift code.” I know I would happily play it.