Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何让 Observable 配合 @escaping 实现传统的回调? #22

Open
wujun4code opened this issue Dec 16, 2017 · 0 comments
Open

如何让 Observable 配合 @escaping 实现传统的回调? #22

wujun4code opened this issue Dec 16, 2017 · 0 comments
Labels

Comments

@wujun4code
Copy link
Member

利用 extension 机制对 Observable 对象进行拓展

import Foundation
import RxSwift

public protocol AVRxCallbackConvertible {
    associatedtype ResultType
    func onExecuted(completion: @escaping (ResultType) -> Void, error: @escaping (Error) -> Void) -> Void
}

public protocol AVRxEventConvertible {
    associatedtype EventArgsType
    func onEventInvoked(received: @escaping (EventArgsType) -> Void) -> Void
}

extension Observable: AVRxCallbackConvertible {
    public typealias ResultType = E

    public func onExecuted(completion: @escaping (Element) -> Void, error: @escaping (Error) -> Void) {

         _ = self.single().subscribe(onNext: { (resultElement) in
            completion(resultElement)
        }, onError: { (er) in
            error(er)
        }, onCompleted: {
        }) {
            print("onExecuted subscription disposed.")
        }
    }
}

extension Observable: AVRxEventConvertible {
    
    public func onEventInvoked(received: @escaping (Element) -> Void) {
        _ = self.subscribe(onNext: { (argsType) in
            received(argsType)
        }, onError: { (_) in

        }, onCompleted: {

        }) {

        }
    }

    public typealias EventArgsType = E
}

使用传统回调方式的代码

    func testCallback() {
        let expert = expectation(description: "Example")
        let todo = AVObject(className: "SwiftTodo")
        todo["foo"] = "bar"
        todo.save().onExecuted(completion: { (object) in
            expert.fulfill()
        }) { (error) in
            XCTFail("Expected getSandwiches to succeed, but it failed. ?")
        }
        waitForExpectations(timeout: 10, handler: nil)
    }

This is the reason why Swift is much better than Objective-C and Java, of course , Rx concept gives another magic point of view to migrate from traditional callback.

@wujun4code wujun4code added the doc label Dec 16, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant