【问题标题】:Combine: Wrapped async call with Future, but Future.sink doesn't appear to complete结合:用 Future 包装异步调用,但 Future.sink 似乎没有完成
【发布时间】:2020-12-21 16:48:32
【问题描述】:

第一次发帖,老读者……我已经打包了一个对 Firebase 授权 API 的异步调用。我从 SwiftUI 视图函数中调用它。

func authenticateFirebaseEmail(email: String, password: String) -> 
    Future<String, Error> {
        return Future<String,Error> {  promise in
                Auth.auth().signIn(withEmail: email, password: password) { result, error in
            if let error=error {
                print("failure detected")
                promise(.failure(error))
            }
            
            if let result=result {
                print("result detected - returning success promise")
                promise(.success(result.user.email!))
            }
            
        }
    }
}
...

func logMeInFuncInView() {
        var cancellable : AnyCancellable?
        cancellable = authenticateFirebaseEmail(email: self.userEmail, password: self.password).map( {
            value in return value
        })
        .sink(receiveCompletion: { (completion) in
            print("completion received")
        }, receiveValue: { user in
            print("value received")
            self.errorMessage = user
            })
    }

控制台输出如下,但从未达到“收到完成”或“收到值”调用: result detected - returning successful promise

是包装后的回调、未来、我使用未来的方式,还是我没有完全看到的问题?

【问题讨论】:

    标签: firebase swiftui future combine


    【解决方案1】:

    您的cancellable 是局部变量,因此一旦脱离上下文就被销毁。一旦订阅者被销毁,它就会取消订阅,因为它只有一个,所以发布者也取消了。

    您的解决方案是让您的可取消属性,即

    var cancellable : AnyCancellable?  // << here !!
    
    func logMeInFuncInView() {
            cancellable = authenticateFirebaseEmail(email: self.userEmail, password: self.password).map( {
                value in return value
            })
            // .. other code
    }
    

    【讨论】:

      猜你喜欢
      • 2016-01-31
      • 1970-01-01
      • 2018-07-30
      • 1970-01-01
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      相关资源
      最近更新 更多