【问题标题】:RxSwift Optimising TriggersRxSwift 优化触发器
【发布时间】:2017-07-12 22:05:11
【问题描述】:

我在应用程序进入前台时执行一项任务。 我还想在我的视图模型初始化后立即执行此任务。

如何编写此代码以避免复制和粘贴任务代码? 目前代码如下所示:

init(dependencies: Dependencies) {
        self.dependencies = dependencies

        dependencies.apiClient.notificationsCount()
            .map { $0.value > 0 ? String($0.value) : nil }
            .bind(to: tabBadgeValue)
            .disposed(by: disposeBag)
        dependencies.notification.notification(for: .appWillEnterForeground)
            .map { _ in () }
            .flatMapLatest(dependencies.apiClient.notificationsCount)
            .map { $0.value > 0 ? String($0.value) : nil }
            .bind(to: tabBadgeValue)
            .disposed(by: disposeBag)
    }

【问题讨论】:

    标签: swift optimization rx-swift


    【解决方案1】:

    您可以使用startWith 在收到第一个通知之前发出下一个事件:

    init(dependencies: Dependencies) {
        self.dependencies = dependencies
    
        dependencies.notification.notification(for: .appWillEnterForeground)
            .map { _ in () }
            .startWith(())
            .flatMapLatest(dependencies.apiClient.notificationsCount)
            .map { $0.value > 0 ? String($0.value) : nil }
            .bind(to: tabBadgeValue)
            .disposed(by: disposeBag)
    }
    

    【讨论】:

    • 这正是我正在寻找的解决方案。
    猜你喜欢
    • 2011-11-13
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多