0

I'm trying to use Action / CocoaAction library. The primary usage for now is to show an UIAlertController and when an UIAlertAction button is tapped it has to call a function defined in my viewModel (changeAddress that returns an Observable).

My understanding of this would be:

let ac = CocoaAction(workFactory: {[unowned self] _ in
    self.viewModel!.requestChangeAddress()
        .subscribeNext({ [unowned self] data in
            if let response = data?.result
            {
                self.showResultOperation(response)
            }
        })
        .addDisposableTo(self.disposeBag)
        return .empty()
    })

let OKAction = UIAlertAction.Action("OK", style: .Default)
OKAction.rx_action = ac

But unfortunately it doesn't work. The workFactory closure is correctly called but the subscription doesn't take effect. I know something is wrong when I return .empty but I cannot understand how to solve.

How can I correct this? What I'm doing wrong?

Zoe
  • 27,060
  • 21
  • 118
  • 148
jerrygdm
  • 450
  • 1
  • 7
  • 22

1 Answers1

0

great question! Thanks for posting the code.

So your code is getting the observable from requestChangeAddress, but then it's subscribing to it and adding it to a dispose bag. The Action class is actually going to take care of that for you, you only need to return the disposable.

The problem is that you want to do something with the values sent on the action, and returning the observable won't let you do that. So you need to include a call to doOnNext in the observer chain. Here's what it might look like:

let ac = CocoaAction(workFactory: {[unowned self] _ in
    return self.viewModel!
        .requestChangeAddress()
        .doOnNext({ [unowned self] data in
            if let response = data?.result
            {
                self.showResultOperation(response)
            }
        })
        .map { _ in Void() }
})

Using doOn functions in RxSwift is a great way to inject side-effects into your observables when necessary, like it is here.

EDIT: I added the map at the end to fix a compiler error, because the return type from the factory method is Observable<Void>.

Ash Furrow
  • 12,391
  • 3
  • 57
  • 92
  • Thanks, I tried doing so but at the first line the complier gives this error: "Cannot convert value of type '(_)->Observable
    ' to expected argument of type '_ -> Observable<_>'"
    – jerrygdm Aug 23 '16 at 21:33
  • Thanks...almost all fine. I have an issue related to this...after tapping ok or cancel in the alertContoller the button looks like disabled, no more touch are firing. How can I solve the problem? – jerrygdm Oct 18 '16 at 08:22