forked from russhwolf/To-Do
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCombineAdapters.swift
45 lines (39 loc) · 1.35 KB
/
CombineAdapters.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import Combine
import shared
// Thanks to Lamert Westerhoff who initially suggested the patterns behind createPublisher() and PublishedFlow to me
func createPublisher<T>(_ flowAdapter: FlowAdapter<T>) -> AnyPublisher<T, KotlinError> {
return Deferred<Publishers.HandleEvents<PassthroughSubject<T, KotlinError>>> {
let subject = PassthroughSubject<T, KotlinError>()
let job = flowAdapter.subscribe { (item) in
let _ = subject.send(item)
} onError: { (error) in
subject.send(completion: .failure(KotlinError(error)))
} onComplete: {
subject.send(completion: .finished)
}
return subject.handleEvents(receiveCancel: {
job.cancel(cause: nil)
})
}.eraseToAnyPublisher()
}
class PublishedFlow<T> : ObservableObject {
@Published
var output: T
init<E>(_ publisher: AnyPublisher<T, E>, defaultValue: T) {
output = defaultValue
publisher
.replaceError(with: defaultValue)
.compactMap { $0 }
.receive(on: DispatchQueue.main)
.assign(to: &$output)
}
}
class KotlinError: LocalizedError {
let throwable: KotlinThrowable
init(_ throwable: KotlinThrowable) {
self.throwable = throwable
}
var errorDescription: String? {
get { throwable.message }
}
}