Hello,
I am using the Combine framework, and I have a question about my implementation. Is it a good practice to embed a view controller presentation in a Future
and wait for this view controller to call back before publishing a value?
The following function will display a view controller (requester), wait for the user to fill the value, and send this value in the promise.
private func requestDisplayName() -> Future<String, Never> {
Future { [weak self] promise in
guard let self = self else { return }
let requester = RequestDisplayNameViewController()
requester.displayName
.dropFirst()
.removeDuplicates()
.receive(on: DispatchQueue.main)
.sink { displayName in
promise(.success(displayName))
}
.store(in: &self.cancellables)
self.mainVC.present(requester, animated: true, completion: nil)
}
}
displayName
is a CurrentValueSubject<String, Never>
that sends a value once the user hit a validate button in the RequestDisplayNameViewController
On the other side, I have an apiObserver
waiting to receive the display name from the server, and once the data obtained, it will check if the value is nil or not, and according to this value, the requestDisplayName()
will be called.
apiObserver.receive(on: DispatchQueue.main)
.flatMap({ displayNameFromServer -> AnyPublisher<String, Never> in
if let displayNameFromServer = displayNameFromServer {
return Result.Publisher(displayNameFromServer).eraseToAnyPublisher()
}
return self.requestDisplayName().eraseToAnyPublisher()
})
.flatMap({ displayName in
// Make an action with the displayName
})
// ..
Thank you.