Prevent JobCancellationException with Cancellable ViewModel
masterWhen subclassing a Kotlin ViewModel in Swift and using Combine to observe flows (especially via KMP-NativeCoroutines), the viewModelScope might be cancelled before the Swift object is deinitialized. This can cause Combine publishers to fail with a JobCancellationException.
To fix this, make your Swift ViewModel conform to Cancellable and perform cleanup in the cancel() function. The library ensures cancel() is called before the ViewModel is cleared.
import Combine
import KMPNativeCoroutinesCombine
import shared
class TimeTravelViewModel: shared.TimeTravelViewModel, Cancellable {
private var cancellables = Set<AnyCancellable>()
override init() {
super.init()
createPublisher(for: currentTimeFlow)
.assertNoFailure()
.sink { time in print("It's \(time)") }
.store(in: &cancellables)
}
func cancel() {
cancellables = []
}
}