Skip to content

Commit

Permalink
End background task as soon as begin task is called
Browse files Browse the repository at this point in the history
  • Loading branch information
laevandus committed Dec 10, 2024
1 parent 40ac335 commit e6e47a2
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 14 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- Add `ChannelListSortingKey.pinnedAt`
- Add `ChatChannel.membership.pinnedAt`
- Add `ChatChannel.isPinned`
### 🐞 Fixed
- Fix a rare issue of not ending background tasks [#3528](https://github.com/GetStream/stream-chat-swift/pull/3528)

# [4.68.0](https://github.com/GetStream/stream-chat-swift/releases/tag/4.68.0)
_December 03, 2024_
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ class IOSBackgroundTaskScheduler: BackgroundTaskScheduler {
}

func beginTask(expirationHandler: (() -> Void)?) -> Bool {
endTask()
activeBackgroundTask = app?.beginBackgroundTask { [weak self] in
expirationHandler?()
self?.endTask()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
//

@testable import StreamChat
import StreamChatTestTools
import XCTest

#if os(iOS)
Expand Down Expand Up @@ -44,22 +45,9 @@ final class IOSBackgroundTaskScheduler_Tests: XCTestCase {
}

func test_whenSchedulerIsDeallocated_backgroundTaskIsEnded() {
// Create mock scheduler type and catch `endTask` invokation
class MockScheduler: IOSBackgroundTaskScheduler {
let endTaskClosure: () -> Void

init(endTaskClosure: @escaping () -> Void) {
self.endTaskClosure = endTaskClosure
}

override func endTask() {
endTaskClosure()
}
}

// Create mock scheduler and catch `endTask`
var endTaskCalled = false
var scheduler: MockScheduler? = MockScheduler {
var scheduler: IOSBackgroundTaskSchedulerMock? = IOSBackgroundTaskSchedulerMock {
endTaskCalled = true
}

Expand All @@ -75,5 +63,30 @@ final class IOSBackgroundTaskScheduler_Tests: XCTestCase {
// Simulate access to scheduler to eliminate the warning
_ = scheduler
}

func test_callingBeginMultipleTimes_allTheBackgroundTasksAreEnded() {
var endTaskCallCount = 0
let scheduler = IOSBackgroundTaskSchedulerMock {
endTaskCallCount += 1
}
_ = scheduler.beginTask(expirationHandler: nil)
_ = scheduler.beginTask(expirationHandler: nil)
_ = scheduler.beginTask(expirationHandler: nil)
XCTAssertEqual(3, endTaskCallCount)
}

// MARK: - Mocks

class IOSBackgroundTaskSchedulerMock: IOSBackgroundTaskScheduler {
let endTaskClosure: () -> Void

init(endTaskClosure: @escaping () -> Void) {
self.endTaskClosure = endTaskClosure
}

override func endTask() {
endTaskClosure()
}
}
}
#endif

0 comments on commit e6e47a2

Please sign in to comment.