0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

幫 InstanceID 加一個 RxSwift 的 Helper Wrapper

Posted at

InstantID 在取用的時候,是以非同步的方式進行,
為了在 RxSwift 程式碼裡面能夠比較順利使用,
就決定來寫個 wrapper 給他!

建立 Protocol

首先習慣上會先新增一個 protocol

protocol InstanceIdFetcherType {
    func fetch() -> Observable<InstanceIDResult>
}

實作

struct InstanceIdFetcher: InstanceIdFetcherType {
    
    static let shared: InstanceIdFetcher = InstanceIdFetcher()
    
    func fetch() -> Observable<InstanceIDResult> {
        return Observable.create { observer in
            InstanceID.instanceID().instanceID { result, error in
                if let result = result {
                    observer.on(.next(result))
                    observer.on(.completed)
                } else if let error = error {
                    observer.on(.error(error))
                } else {
                    observer.on(.completed)
                }
            }
            
            return Disposables.create()
        }
    }
}

使用

let fetchToken = buttonTapped
    // 省略防止按鈕連打的處理
    .flatMapLatest { _ in
        InstanceIdFetcher.shared // 便利上在這邊這樣寫,實際上這個變數可以用 DI 的方式注入 view model
            .fetch()
            .catchError { _ in .empty() } // 可以在這裡處理錯誤回應
    }
    .map { $0.token } // 可以這樣取得實際回傳的 token
    // 接著再看要拿 token 拿來做什麼事,例如回傳到 server 端等等
    .share()

環境

  • Xcode 10.3 (10G8)
  • Swift 5
  • Libraries
    • RxSwift 5.0.0
    • FirebaseInstanceID 4.2.3

最後

如果內文需要更新、有錯誤或容易誤解的地方,歡迎發修改或是留言告訴我!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?