Created
December 5, 2021 14:32
-
-
Save danielt1263/0e9e132028a1bfc1d5139ac523f7a206 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ActivityTracker.swift | |
// | |
// Created by Daniel Tartaglia on 05 Dec 2021. | |
// Copyright © 2021 Daniel Tartaglia. MIT License. | |
// | |
extension Publisher { | |
func trackActivity(_ activityTracker: ActivityTracker) -> AnyPublisher<Output, Failure> { | |
activityTracker.trackActivity(of: self) | |
} | |
} | |
final class ActivityTracker { | |
let isActive: AnyPublisher<Bool, Never> | |
private let subject = CurrentValueSubject<Int, Never>(0) | |
private let lock = NSRecursiveLock() | |
init() { | |
isActive = subject | |
.map { $0 > 0 } | |
.removeDuplicates() | |
.eraseToAnyPublisher() | |
} | |
func trackActivity<Pub>(of pub: Pub) -> AnyPublisher<Pub.Output, Pub.Failure> where Pub: Publisher { | |
Publishers.Using( | |
{ () -> AnyCancellable in | |
self.increment() | |
return AnyCancellable({ self.decrement() }) | |
}, | |
publisherFactory: { _ in pub } | |
) | |
.eraseToAnyPublisher() | |
} | |
private func increment() { | |
lock.lock() | |
subject.send(subject.value + 1) | |
lock.unlock() | |
} | |
private func decrement() { | |
lock.lock() | |
subject.send(subject.value - 1) | |
lock.unlock() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment