Why observeValues block not called? - swift

Try to use ReativeSwift on my project, but something not perform well
I have check many times, cant find out what's wrong.
Everything is right, and it just not called.
class MSCreateScheduleViewModel: NSObject {
var scheduleModel = MSScheduleModel()
var validateAction: Action<(), Bool, NoError>!
override init() {
super.init()
validateAction = Action(execute: { (_) -> SignalProducer<Bool, NoError> in
return self.valiateScheduleModel()
})
validateAction.values.observeValues { (isok) in
print("isok??") //this line not called
}
validateAction.values.observeCompleted {
print("completed") //this line not called
}
}
func valiateScheduleModel() -> SignalProducer<Bool, NoError> {
let (signal, observer) = Signal<Bool, NoError>.pipe()
let signalProducer = SignalProducer<Bool, NoError>(_ :signal)
observer.send(value: true) //this line called
observer.sendCompleted() //this line called
return signalProducer
}
}

When you create a SignalProducer by wrapping an existing signal as you do in valiateScheduleModel, the producer observes the signal when it is started and forwards the events. The problem in this case is that the signal completes before the producer is ever returned from the function and started, and so no events are forwarded.
If you want to create a producer that immediately sends true and completes when it is started, then you should do something like this:
func valiateScheduleModel() -> SignalProducer<Bool, NoError> {
return SignalProducer<Bool, NoError> { observer, lifetime in
observer.send(value: true)
observer.sendCompleted()
}
}
The closure will not be executed until the producer is started, and so the Action will see the events.

Related

Question about the conditional sentence of Observable. (RxSwift)

I tried to create a function runsample() that uses multiple observables as below.
If I meet a specific condition in the middle of the stream, I want to start from the beginning of function.
(foo1() in the example below)
In this case, how do I modify the runsample() function?
class SampleClass {
////////////////////////////////
// private
////////////////////////////////
private func foo1() -> Observable<String> {
// Do something
return .just("TEST")
}
private func foo2() -> Observable<Bool> {
// Do something
return .just(false) // or true
}
private func foo3() -> Observable<String> {
// Do something
return .just("Result")
}
////////////////////////////////
// public
////////////////////////////////
public func runSample() -> Observable<String> {
return Observable.just(())
.flatMap { [unowned self] _ in
self.foo1()
}
.flatMap { [unowned self] _ in
self.foo2()
}
// I want to retry foo1() when foo2() is false
// I want to make foo3() run only if foo2() is true.
.flatMap { [unowned self] _ in
self.foo3()
}
}
}
Based on your comment, this is what you want:
func runSample() -> Observable<String> {
struct NotValid: Error { }
return Observable.deferred {
foo1().flatMap { _ in
foo2().do(onNext: { isValid in
if !isValid { throw NotValid() }
})
}
}
.retry()
.flatMap { _ in foo3() }
}
It's a very strange requirement you have, but it's doable. I expect this is an X-Y problem though.
You really want to retry foo1()? That would imply that it failed but it obviously didn't. In any case, this will do what you want:
func runSample() -> Observable<String> {
foo1()
.flatMap { [foo2] _ in
foo2()
}
.flatMap { [foo1, foo3] isTrue in
isTrue ? foo3() : foo1()
}
}
This function will return an Observable. Every time that Observable is subscribed to, the first foo1() will be activated.
Every time the first foo1() emits a value, the value will be ignored (which is quite odd) and foo2() will be called. This will generate a new Observable which will be subscribed to.
Whenever any of the Observables generated by foo2() emit a value, if the value is true foo3() will be called, otherwise foo1() will be called. Whichever one is called, its Observable will be subscribed to.
The entire function will emit all the values that any foo1()s or foo3()s Observables emit.
Importantly for this example, you do not need to start with Observable.just(()).
Thinking about it, I'd prefer something like this:
func runSample() -> Observable<String> {
Observable.zip(foo1(), foo2())
.flatMap { $0.1 ? foo3() : .just($0.0) }
}
That way I don't have to run foo1() twice.

Rxswift Map and Zip not Called

I am trying to get the element of 2 observables produced asynchronously and pass them as parameters to a function once both are received.
However my map operator in my ViewModel below is not executed and the breakpoint just skips over it.
ViewModel.swift
init(api: ApiService) {
self.api = api
}
func getData1() -> Observable<Data1> {
return api.getData1()
}
func getData2() -> Observable<NewViewModel> {
return Observable.create { observer in
let disposable = Disposables.create()
self.api.getData2()
.map {
$0.arrayOfStuff.forEach { (stuff) in
let background = stuff.background
let newViewModel = NewViewModel( background: self.spotlightBackground)
observor.onNext(newViewModel)
}
return disposable
}
}
In my ViewController i am creating the Zip of the observables because newViewModel[getData2] may return later and i want to call the function when both observables emit a value
in my viewDidLoad() i setup zip by subscribing and adding observables
let zippy = Observable.zip(viewModel.getData1(), viewModel.getData2()).subscribe(onNext: { (data1, newViewModel) in
self.layoutSetUp(data1: data1, newViewModel: newViewModel)
})
zippy.disposed(by: disposeBag)
private func layoutSetUp(data1: Data1, newViewModel: NewViewModel) {
DispatchQueue.main.async {
self.view = SwiftUIHostingView(rootView: SwiftUIContentView(data1: data1, newViewModel: newViewModel))
}
}
This is not executing and no values are passed to function either and im not sure why
Your getData2 method never emits a value so neither will the zip. The code in the method is a bit too muddled for me to understand what you are trying to do so I can't tell you exactly what you need, but I can say that when you have an observable that nothing is subscribed to, then it will not emit a value.
This bit:
self.api.getData2()
.map {
$0.arrayOfStuff.forEach { (stuff) in
let background = stuff.background
let newViewModel = NewViewModel(background: self.spotlightBackground)
observor.onNext(newViewModel)
}
return disposable
}
Is an observable with no subscribers.

Swift Combine alternative to Rx Observable.create

I have some code that is built using RxSwift, and I'm playing around with converting it to use Apple's Combine framework.
One pattern which is very common is the use of Observable.create for one-shot observables (usually network requests). Something like this:
func loadWidgets() -> Observable<[Widget]> {
return Observable.create { observer in
// start the request when someone subscribes
let loadTask = WidgetLoader.request("allWidgets", completion: { widgets in
// publish result on success
observer.onNext(widgets)
observer.onComplete()
}, error: { error in
// publish error on failure
observer.onError()
})
// allow cancellation
return Disposable {
loadTask.cancel()
}
}
}
I'm trying to map that across to Combine and I haven't been able to quite figure it out. The closest I've been able to get is using Future for something like this:
func loadWidgets() -> AnyPublisher<[Widget], Error> {
return Future<[Widget], Error> { resolve in
// start the request when someone subscribes
let loadTask = WidgetLoader.request("allWidgets", completion: { widgets in
// publish result on success
resolve(.success(widgets))
}, error: { error in
// publish error on failure
resolve(.failure(error))
})
// allow cancellation ???
}
}
As you can see, it does most of it, but there's no ability to cancel.
Secondarily, future doesn't allow multiple results.
Is there any way to do something like the Rx Observable.create pattern which allows cancellation and optionally multiple results?
I think I found a way to mimic Observable.create using a PassthroughSubject in Combine. Here is the helper I made:
struct AnyObserver<Output, Failure: Error> {
let onNext: ((Output) -> Void)
let onError: ((Failure) -> Void)
let onComplete: (() -> Void)
}
struct Disposable {
let dispose: () -> Void
}
extension AnyPublisher {
static func create(subscribe: #escaping (AnyObserver<Output, Failure>) -> Disposable) -> Self {
let subject = PassthroughSubject<Output, Failure>()
var disposable: Disposable?
return subject
.handleEvents(receiveSubscription: { subscription in
disposable = subscribe(AnyObserver(
onNext: { output in subject.send(output) },
onError: { failure in subject.send(completion: .failure(failure)) },
onComplete: { subject.send(completion: .finished) }
))
}, receiveCancel: { disposable?.dispose() })
.eraseToAnyPublisher()
}
}
And here is how it looks in usage:
func loadWidgets() -> AnyPublisher<[Widget], Error> {
AnyPublisher.create { observer in
let loadTask = WidgetLoader.request("allWidgets", completion: { widgets in
observer.onNext(widgets)
observer.onComplete()
}, error: { error in
observer.onError(error)
})
return Disposable {
loadTask.cancel()
}
}
}
From what I've learned, the support for initializing an AnyPublisher with a closure has been dropped in Xcode 11 beta 3. This would be a corresponding solution for Rx's Observable.create in this case, but for now I believe that the Future is a goto solution if you only need to propagate single value. In other cases I would go for returning a PassthroughSubject and propagating multiple values this way, but it will not allow you to start a task when the observation starts and I believe it's far from ideal compared to Observable.create.
In terms of cancellation, it does not have an isDisposed property similar to a Disposable, so it's not possible to directly check the state of it and stop your own tasks from executing. The only way that I can think of right now would be to observe for a cancel event, but it's surely not as comfortable as a Disposable.
Also, I'd assume that cancel might in fact stop tasks like network requests from URLSession based on the docs here: https://developer.apple.com/documentation/combine/cancellable
Add an isCancelled operation outside the closure and check it in the future's closure. isCancelled can be toggled with the handleEvent() operator.
var isCancelled = false
func loadWidgets() -> AnyPublisher<[Widget], Error> {
return HandleEvents<Future<Any, Error>> { resolve in
// start the request when someone subscribes
let loadTask = WidgetLoader.request("allWidgets", completion: { widgets in
// publish result on success
resolve(.success(widgets))
}, error: { error in
// publish error on failure
resolve(.failure(error))
}
if isCancelled {
loadTask.cancel()
}
).handleEvents(receiveCancel: {
isCancelled = true
})
}
}
and somewhere in the app you do this to cancel the event
loadWidgets().cancel()
Also check this article
Thanks to ccwasden for the inspiration. This replicates Observable.create semantics with a pure Combine implementation without any superfluous entities.
AnyPublisher.create() Swift 5.6 Extension
public extension AnyPublisher {
static func create<Output, Failure>(_ subscribe: #escaping (AnySubscriber<Output, Failure>) -> AnyCancellable) -> AnyPublisher<Output, Failure> {
let passthroughSubject = PassthroughSubject<Output, Failure>()
var cancellable: AnyCancellable?
return passthroughSubject
.handleEvents(receiveSubscription: { subscription in
let subscriber = AnySubscriber<Output, Failure> { subscription in
} receiveValue: { input in
passthroughSubject.send(input)
return .unlimited
} receiveCompletion: { completion in
passthroughSubject.send(completion: completion)
}
cancellable = subscribe(subscriber)
}, receiveCompletion: { completion in
}, receiveCancel: {
cancellable?.cancel()
})
.eraseToAnyPublisher()
}
}
Usage
func doSomething() -> AnyPublisher<Int, Error> {
return AnyPublisher<Int, Error>.create { subscriber in
// Imperative implementation of doing something can call subscriber as follows
_ = subscriber.receive(1)
subscriber.receive(completion: .finished)
// subscriber.receive(completion: .failure(myError))
return AnyCancellable {
// Imperative cancellation implementation
}
}
}

PromiseKit with optional promises

I am currently investigating if I should integrate PromiseKit in an existing project.
My main issue is that I need to implement a business logic that can call up to 5 web-services. Some of them are called depending on the result of previous ones.
My current architecture is based on breaking up the code in several functions with closures that call each other.
I am trying to find out if I could write an easier to manage code with PromiseKit (or anything else).
Here is some pseudo-code of what I need done:
// if true, the phone validation is skipped
let forceRequest = false
// true if a 3rd party web-service has checked the phone number
let isVerified = true
// true if the 3rd party checked the phone number and it is valid
var isValid = false
if !isVerified {
// update value from 3rd party web-service
isValid = isValidPhoneNumberPromise()
}
// If the phone no is invalid stop execution (unless forced)
if !isValid && !force {
throw MyError.error1
}
// web request to create order
createOrderPromise()
// if we have a valid phone number, first send an SMS, then update log
if isValid {
sendSmsPromise()
updateLogPromise()
}
Based on totiG's answer, I came with the following variation:
var isValid = isValid
firstly
{
return Controller.verify(isVerified: isVerified, isValid: isValid)
}
.then { _isValid -> Promise<Int> in
isValid = _isValid
return Controller.createOrder()
}
.then
{ _ -> Promise<Bool> in
if isValid {
return Controller.isSendSms()
}
return Promise (value: true)
}
.then
{ _ -> Promise<Bool> in
if isValid {
return Controller.updateLog()
}
return Promise (value: true)
}
.catch
{ error in
print (error)
}
Yes you can do this using PromiseKit. I have written a basic example showing what you might need. Remember that you would throw an Error when a step fails and handle those failures in the catch block. In my example the verify step passes, but if isValidPhoneNumber was called it would stop the other steps from running. Where I have put the Promise(value: ) you would put your actual web service calls. If the final step to update log is always required to run, you could put this in a .always
enum Errors: Error {
case invalidPhone
case orderFailed
}
func orderPromise() {
firstly {
self.verify(isVerified: false, force: true)
}.then { _ in
self.createOrder()
}.then { orderNumber in
self.sendSms(orderNumber: orderNumber)
}.then { smsSent in
self.updateLog(smsSent: smsSent)
}.catch { error in
//Do something with the error
}
}
private func verify(isVerified: Bool, force: Bool) -> Promise<Bool> {
if isVerified || force {
return Promise(value: true)
}
return isValidPhoneNumber()
}
private func isValidPhoneNumber() -> Promise<Bool> {
return Promise(error: Errors.invalidPhone) //Assume that this fails, then catch in 'orderPromise' will be run
}
private func createOrder() -> Promise<String> {
//Assume an order number is being passed back to use in the message
return Promise(value: "Order100")
}
private func sendSms(orderNumber: String) -> Promise<Bool> {
return Promise(value: true)
}
private func updateLog(smsSent: Bool) -> Promise<Bool> {
return Promise(value: true)
}

Observable returned from function never sends onNext

I have and observable that never sends onNext if its returned by a function, but if i subscribe to it in the function that returns it, onNext is called.
class InfoViewModel {
func refreshPushToken() {
PushNotificationService.sharedInstance.pushToken!
.flatMapLatest { (pushToken: String) -> Observable<Result<User>> in
return UserService.registerPushToken(pushToken)
}
.subscribe { (event ) in
print(event)
}
.addDisposableTo(disposeBag)
}
}
struct UserService {
....
static func registerPushToken(_ pushToken: String) -> Observable<Result<User>> {
...
return self.postUser(user: user)
}
static fileprivate func postUser(user: User) -> Observable<Result<User>> {
let rxProvider: RxMoyaProvider<Backend> = RxMoyaProvider<Backend>(endpointClosure: Backend.endpointClosure)
return rxProvider.request(Backend.register(user: user))
.mapObject(type: User.self)
.map({ (user: User) -> Result<User> in
LogService.log(level: .debug, action: "postUser", message: "Posted user with success", parameters: ["user": user.deviceId])
return .success(user)
})
.catchError({ error -> Observable<Result<User>> in
LogService.log(level: .error, action: "postUser", message: "Error posting user", parameters: ["user": user.deviceId, "error": error.localizedDescription])
return Observable.just(.failure(error))
})
}
}
But if I do this
rxProvider.request(Backend.register(user: user))
...
.subscribe { (event ) in
print(event)
}
in the UserService, i will get a next event.
I have tried to use debug() on the observable in InfoViewModel, there is a subscription, i just never receive any events.
So i figured it out, I was creating the RxMoyaProvider inside the method, so as soon as i went out of the scope of the method, it was deallocated. Which means that when was subscribing to it, it could no longer create the request. The reason that this wouldn't fail is because of how the observable is created
open func request(_ token: Target) -> Observable<Response> {
// Creates an observable that starts a request each time it's subscribed to.
return Observable.create { [weak self] observer in
let cancellableToken = self?.request(token) { result in
switch result {
case let .success(response):
observer.onNext(response)
observer.onCompleted()
case let .failure(error):
observer.onError(error)
}
}
return Disposables.create {
cancellableToken?.cancel()
}
}
}
As you can see, the request is called upon subscription, but since self had been deallocated the request was never fired. And all i got back was an empty observable.