Infinity James
Infinity James

Reputation: 4735

RxSwift Optimising Triggers

I perform a task when the application enters the foreground. I also want to perform this task as soon as my view model is initialised.

How can I write this to avoid copy and pasting the task code? Currently the code looks like this:

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)
    }

Upvotes: 1

Views: 52

Answers (1)

joern
joern

Reputation: 27620

You could use startWith to emit a next event before receiving the first notification:

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)
}

Upvotes: 1

Related Questions