A Preliminary Trial of RxSwift, RxBlocking and RxTest

Keywords: Swift Android iOS network

RxJava has become one of the most important components of Android development. Recently, iOS applications have been developed using Swift. Consider using RxSwift in architecture design.

Add dependency
# Podfile
use_frameworks!

target 'YOUR_TARGET_NAME' do
    pod 'RxSwift', '~> 5'
    pod 'RxCocoa', '~> 5'
    pod 'RxBlocking', '~> 5'
end

# RxTest and RxBlocking make the most sense in the context of unit/integration tests
target 'YOUR_TESTING_TARGET' do
    
    pod 'RxTest', '~> 5'
end
Create Observable
import RxSwift
...

let observable = Observable<Int>.create { (observer) -> Disposable in
    observer.onNext(1)
    observer.onCompleted()
    return Disposables.create()
}
Define onError calls
struct MyError:Error {
    var message = ""
    init(message:String) {
        self.message = message
    }
}
let observable = Observable<Int>.create { (observer) -> Disposable in
    let error = MyError(message: "Test Error")
    observer.onError(error)
    return Disposables.create()
}
subscribe

Define only one callback

observable.subscribe({ it in
    print("onNext \(it.element)")
})

Define onNext and onError

observable.subscribe(onNext: { it in
    print("onNext \(it)")
},onError: { error in
    print((error as! MyError).message)
})

Define onNext, onError, and onCompleted

observable.subscribe(onNext: { it in
    print("onNext \(it)")
},onError: { error in
    print((error as! MyError).message)
},onCompleted: {

})

RxBlocking

RxBlocking is another separate framework in RxSwift. Like RxTest, pod is required to be introduced into the framework, and dependencies need to be added separately. RxBlocking can change RxSwift from asynchronous response to synchronous response, so RxBlocking is mostly used for unit testing.

    pod 'RxBlocking'
import RxSwift
import RxBlocking
...

do{
    let result = try observable.toBlocking().first()
    print("Result:\(result)")
}catch{
    print((error as! MyError).message)
}
Application scenario

For example, we use RxSwift to upload pictures. When publishing dynamic pictures, we need to upload pictures first and then call network requests based on RxSwift. Plus, if we don't want to nest calls, we can call them synchronously through toBlocking.

RxTest

RxTest is a package that can be used to build RxSwift automated testing. It needs to be introduced into the framework of pod separately.

Posted by nagasea on Wed, 02 Oct 2019 19:55:37 -0700