How to translate if-else to RxSwift?

I am trying to learn the RxSwift library

I have a code like this:

if data.checkAllIsOk()
{ 
    [do things]
}
else
{ 
    [show alert]
}

Now I need to update the data from the server before checking, so I modeled getData () that returns an Observable.

My current approach is this:

getData()  
    >- flatMap{ (data:Data) -> Observable<Bool> in
        _=0 // workaround for type inference bugs
        return just(data.checkAllIsOk())
    }
    >- subscribeNext{ (ok) -> Void in
        if ok
        {
            [do the things]
        }
        else
        {
            [show the alert]
        }
    } 
    >- disposeBag.addDisposable()

It works (or it should, I still write it), but it feels wrong .. is there a more "reactive" way to do this? What are the most suitable operators?

Perhaps it returns an error for "false" and uses a catch block?

Update

Following the approach suggested by ssrobbi i, we divided 2 branches into 2 different subscribeNext and used a filter to select a positive or negative branch. This is the result:

let checkData=getData()  
        >- flatMap{ (data:Data) -> Observable<Bool> in
            _=0 
            return just(data.checkAllIsOk())
        }
        >- shareReplay(1)
}
[...]
checkData
    >- filter{ (ok) -> Bool in
        ok == true
    }
    >- subscribeNext{ (_) -> Void in
        [do the things]
    }
    >- disposeBag.addDisposable()

checkData
    >- filter{ (ok) -> Bool in
        ok == false
    }
    >- subscribeNext{ (_) -> Void in
        [show the alert]
    } 
    >- disposeBag.addDisposable()

, , ( !)

RxSwift slack shareReplay (1), getData() .

+4
4

, , , RxSwift ( - , BS), , , .

, , , "". , , , , , - . , , getData, , getData , ( , ..), .

: , , , , , , , , -. ( )

: , , -.


, , getData(), , , . - . , .

: , if, , , .

+5

getData() Observable<Data>, . , getData() , data.checkAllIsOk() , , true.

getData() - ( Rx v2 Swift v2):

getData().subscribe { event in 
switch event {
case .Next(let data):
    [do things with data]
case .Error(let error):
    [show the alert]
}
+3

RXSwift, ( RXSwift). if else , , , .

if else condition ? a : b, (Haskell, ). , , ;)

+2

, checkData Observable<Bool>, " -" .

, , ( ):

func isDataOk(_ data: Data) -> Bool { /* ... */ }

let data = getData().shareReplay(1)

let goodData = data.filter(isDataOk)
let badData = data.filter{ isDataOk($0) == false }

goodData
  .subscribe( /* do stuff */ )
  .addDisposableTo(disposeBag)

badData
  .subscribe( /* show alert */ )
  .addDisposableTo(disposeBag)

But I agree with Daniel that this is a great opportunity to use the observed errors. Something like that:

func passOrThrow(_ data: Data) throws -> Data { /* throw an error here if data is bad */ }

getData()
  .map(passOrThrow)
  .subscribe(onNext: { data in
    // do the things
  }, onError: { error in
    // show the alert
  }).addDisposableTo(disposeBag)
+1
source

Source: https://habr.com/ru/post/1605599/


All Articles