如何使用ReactiveSwift和Firebase异步方法调用处理SignalProducer?

时间:2017-05-17 10:11:32

标签: ios firebase swift3 reactive-swift

我正在开发一个使用Swift 3的iOS应用程序,使用ReactiveSwift 1.1.1,MVVM + Flow Coordinator模式和Firebase作为后端。我最近才开始适应FRP,我仍在努力弄清楚如何将新功能集成到我现有的代码库中。

例如,我的模型使用Firebase中的异步方法从Web下载缩略图,我想提供SignalProducer<Content, NoError>来订阅我的ViewModel类并观察是否已下载缩略图,然后更新UI。

// field to be used from the view-models to observe
public let thumbnailContentSignalProducer = SignalProducer<Content, NoError> { (observer, disposable) in
    // TODO: send next content via completion below
} 

// thumbnail download method
public func findThumbnail(bucketId: String, contentId: String) {
    guard let userId = userService.getCurrentUserId() else {
        debugPring("Error id")
        return
    }

    let ref = self.storageThumbnail.reference()
    let contentRef = ref
        .child(userId)
        .child(bucketId)
        .child(FirebaseConstants.pathImages)
        .child("\(contentId).jpg")

    contentRef.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) in
        guard let data = data else {
            debugPrint("Error download")
            return
        }
        let content = Image(data: data)
        content.id = contentId
        content.userId = userId
        content.bucketId = bucketId

        // TODO: emit signal with content
        // How to send the content via the SignalProducer above?
    })
}

我也尝试过与Signal<Content, NoError>类似的东西,而我使用Signal<Content, NoError>.pipe()方法接收(observer, disposable)元组,并将观察者保存为私有全局字段以从中访问它Firebase回调。

问题:

这是正确的做法还是我错过了什么?

如何在完成时发出内容对象?

更新

经过几个小时的痛苦,我发现了如何设计SingalProducer以发出信号并从ViewModel订阅。

也许以下代码段也可以帮助其他代码:

// model protocol
import ReactiveSwift
import enum Result.NoError

public protocol ContentService {
    func findThumbnail(bucketId: String, contentId: String)
    var thumbnailContentProducer: SignalProducer<Content, NoError> { get }
}


// model implementation using firebase
import Firebase
import FirebaseStorage
import ReactiveSwift

public class FirebaseContentService: ContentService {

    // other fields, etc.
    // ...

    private var thumbnailContentObserver: Observer<Content, NoError>?
    private var thumbnailContentSignalProducer: SignalProducer<Content, NoError>?
    var thumbnailContentProducer: SignalProducer<Content, NoError> {
        return thumbnailContentSignalProducer!
    }

    init() {
        thumbnailContentSignalProducer = SignalProducer<Content, NoError> { (observer, disposable) in
            self.thumbnailContentObserver = observer
        }
    }

    func findThumbnail(bucketId: String, contentId: String) {
        guard let userId = userService.getCurrentUserId() else {
            // TODO handle error
            return
        }

        let ref = self.storageThumbnail.reference()
        let contentRef = ref
            .child(userId)
            .child(bucketId)
            .child(FirebaseConstants.pathImages)
            .child("\(contentId).jpg")

        contentRef.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) in
            guard let data = data else {
                // TODO handle error
                return
            }
            let content = Image(data: data)
            content.id = contentId
            content.userId = userId
            content.bucketId = bucketId
            // emit signal
            self.thumbnailContentObserver?.send(value: content)
        })
    }
}


// usage from a ViewModel
contentService.thumbnailContentProducer
    .startWithValues { content in
        self.contents.append(content)
    }

也许有人可以验证上面的代码,并说这是正确的方法。

1 个答案:

答案 0 :(得分:1)

当您考虑将Signalpipe一起使用时,我认为您走的是正确的道路。关键是您需要为每个缩略图请求创建一个新的SignalProducer,并且您需要一种方法将所有这些请求组合成一个结果信号。我正在考虑这样的事情(注意这是未经测试的代码,但它应该得到这个想法):

class FirebaseContentService {
    // userService and storageThumbnail defined here
}

extension FirebaseContentService: ReactiveExtensionsProvider { }

extension Reactive where Base: FirebaseContentService {
    private func getThumbnailContentSignalProducer(bucketId: String, contentId: String) -> SignalProducer<Content, ContentError> {
        return SignalProducer<Content, ContentError> { (observer, disposable) in
            guard let userId = self.base.userService.getCurrentUserId() else {
                observer.send(error: ContentError.invalidUserLogin)
                return
            }

            let ref = self.base.storageThumbnail.reference()
            let contentRef = ref
                .child(userId)
                .child(bucketId)
                .child(FirebaseConstants.pathImages)
                .child("\(contentId).jpg")

                contentRef.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) in
                guard let data = data else {
                    observer.send(error: ContentError.contentNotFound)
                    return
                }
                let content = Image(data: data)
                content.id = contentId
                content.userId = userId
                content.bucketId = bucketId

                observer.send(value: content)
                observer.sendCompleted()
            })
        }
    }
}

class ThumbnailProvider {
    public let thumbnailSignal: Signal<Content, NoError>

    private let input: Observer<(bucketId: String, contentId: String), NoError>

    init(contentService: FirebaseContentService) {
        let (signal, observer) = Signal<(bucketId: String, contentId: String), NoError>.pipe()

        self.input = observer
        self.thumbnailSignal = signal
            .flatMap(.merge) { param in
                return contentService.reactive.getThumbnailContentSignalProducer(bucketId: param.bucketId, contentId: param.contentId)
                    .flatMapError { error in
                        debugPrint("Error download")
                        return SignalProducer.empty
                    }
            }
    }

    public func findThumbnail(bucketId: String, contentId: String) {
        input.send(value: (bucketId: bucketId, contentId: contentId))
    }
}

像这样使用ReactiveExtensionsProvider是通过reactive属性将反应API添加到现有功能的惯用方法。

实际的请求代码仅限于getThumbnailContentSignalProducer,它为每个请求创建一个SignalProducer。请注意,此处会传递错误,稍后会处理和转换为NoError

findThumbnails只需bucketIdcontentId,然后通过输入可观察对象发送。

thumbnailSignalinit的构造是神奇发生的地方。每个输入(包含bucketIdcontentId的元组)都会通过flatMap转换为请求。请注意,.merge策略意味着以请求完成的任何顺序尽快发送缩略图。如果您想确保缩略图按照请求的顺序返回,您可以使用.concat

flatMapError是处理潜在错误的地方。在这种情况下,它只是打印&#34;错误下载&#34;什么都不做。