mirror of
https://github.com/samsonjs/samhuri.net.git
synced 2026-04-27 14:57:40 +00:00
Explain cancellables in AsyncMonitor and NotificationSmuggler post
This commit is contained in:
parent
46a355cfba
commit
f37eb4c7e7
1 changed files with 22 additions and 2 deletions
|
|
@ -45,16 +45,36 @@ The `monitor` method creates a `Task` internally and handles cleanup when the ca
|
||||||
You're free to do the usual `[weak self]` and `guard let self else { return }` dance, but there's a variant that accepts a context parameter that's automatically weakified. Your closure receives a strong reference:
|
You're free to do the usual `[weak self]` and `guard let self else { return }` dance, but there's a variant that accepts a context parameter that's automatically weakified. Your closure receives a strong reference:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
NotificationCenter.default
|
let cancellable = NotificationCenter.default
|
||||||
.notifications(named: .NSCalendarDayChanged)
|
.notifications(named: .NSCalendarDayChanged)
|
||||||
.map(\.name)
|
.map(\.name)
|
||||||
.monitor(context: self) { _self, _ in
|
.monitor(context: self) { _self, _ in
|
||||||
_self.dayChanged()
|
_self.dayChanged()
|
||||||
}.store(in: &cancellables)
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The monitor finishes automatically after finding a nil context.
|
The monitor finishes automatically after finding a nil context.
|
||||||
|
|
||||||
|
### Cancellation tokens
|
||||||
|
|
||||||
|
Similar to Combine there's the concept of a cancellable that ties the observation to the lifetime of that cancellable instance. And of course, we call it a dispose bag. Just kidding obviously, it's called `AsyncCancellable` and there's an `AnyAsyncCancellable` type-erasing wrapper. So very much like Combine you write this:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
import AsyncMonitor
|
||||||
|
|
||||||
|
class Whatever {
|
||||||
|
private var cancellables: Set<AnyAsyncCancellable> = []
|
||||||
|
|
||||||
|
func something() {
|
||||||
|
NotificationCenter.default
|
||||||
|
.notifications(named: .NSCalendarDayChanged)
|
||||||
|
.map(\.name)
|
||||||
|
.monitor { _ in /* ... */ }
|
||||||
|
.store(in: &cancellables)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### KVO
|
### KVO
|
||||||
|
|
||||||
Sometimes you need KVO and the old ways are best. There's a KVO extension that bridges to async sequences:
|
Sometimes you need KVO and the old ways are best. There's a KVO extension that bridges to async sequences:
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue