logo
down
shadow

rxswift error handle issue


rxswift error handle issue

Content Index :

rxswift error handle issue
Tag : swift , By : S. Fenz
Date : November 28 2020, 09:01 AM

I wish this help you I suggest to make the type of createObservable PublishSubject>, instead of BehaviorSubject which, I guess, accidentally flattens two Rx streams conceptually separatable each other: the saveObject process itself (an one-shot process) and starting the saveObject process initiated by user action repeatedly. I've written a short example to demonstrate it.
let createObservable = PublishSubject<Observable<Int>>()

override func viewDidLoad() {
    super.viewDidLoad()
    createObservable.flatMap {
        $0.map { obj in
            print("success: \(obj)")
        }
        .catchError { err in
            print("failure: \(err)")
            return empty()
        }
    }.subscribe()
}

// Simulates an asynchronous proccess to succeed.
@IBAction func testSuccess(sender: UIView!) {
    let oneShot = PublishSubject<Int>()
    createObservable.onNext(oneShot)
    callbackAfter3sec { res in
        oneShot.onNext(1)
        oneShot.onCompleted()
    }
}

// Simulates an asynchronous process to fail.
@IBAction func testFailure(sender: UIView!) {
    let oneShot = PublishSubject<Int>()
    createObservable.onNext(oneShot)
    callbackAfter3sec { res in
        oneShot.onError(NSError(domain: "Error", code: 1, userInfo: nil))
    }
}

func callbackAfter3sec(completion: Int -> ()) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC * 3)), dispatch_get_main_queue()) {
        completion(2)
    }
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

handle nested observables in RxSwift


Tag : ios , By : dexteryy
Date : March 29 2020, 07:55 AM
should help you out You will want to use flatMap
The closure passed to flatMap will return an observable. flatMap will then take care of un-nesting it, meaning if the closure returns a value of type Observable, and you call flatMap on a value of type Observable, the resulting observable will be Observable (an not Observable>
facebookProvider.validate().flatMap { [weak self] _ in
  return self?.loginViewModel.retrieveUserData()
}.subscribe { event in
  switch event {
    // ...
  }
}.addDisposableTo(disposeBag)
public func retrieveUserData(token: String) -> Observable<User> {
    return Network.provider
            .request(.auth(fbToken:  token)).retry(5).debug().mapObject(User.self)
}
facebookProvider.validate().flatMap { [weak self] token in
  return self?.loginViewModel.retrieveUserData(token: token)
}.subscribe { event in
  switch event {
    // ...
  }
}.addDisposableTo(disposeBag)

Tag : ios , By : tjh0001
Date : March 29 2020, 07:55 AM
This might help you The behavior you are seeing is exactly how the search bar delegate works. Instead of making your network request when textDidEndEditing fires, connect it to searchButtonClicked.

Handle Connection Error in UITableView Binding (Moya, RxSwift, RxCocoa)


Tag : ios , By : Priyatna Harun
Date : March 29 2020, 07:55 AM
will be helpful for those in need You aren't handling errors anywhere. I mean you are acknowledging the error in the do operator but that doesn't actually handle it, that just allows it to pass through to the table view, which can't handle an error.
Look up the catchError series of operators for a solution. Probably .catchErrorJustReturn([]) will be all you need.
fileprivate func getNextState() {
    showFullPageState(State.LOADING)
    let products = viewModel.getProductListByID(orderGroup: OrderGroup.SERVICES.rawValue)
        .share()

    products
        .catchError { _ in Observable.never() }
        .filter { $0.products != nil }
        .map { $0.products! }
        .bind(to: tableView!.rx.items(cellIdentifier: cellIdentifier, cellType: ProductCell.self)) {
            (row, element, cell) in
            self.showFullPageState(State.CONTENT)
            cell.product = element
        }
        .disposed(by: bag)

    products
        .subscribe(onError: { error in
            showStatusError(error: error)
            self.showFullPageState(State.CONTENT)
        })
        .disposed(by: bag)

    self.tableView?.rx.setDelegate(self).disposed(by: bag)
}

How to handle error from api request properly with RxSwift in MVVM?


Tag : swift , By : Mahesh
Date : March 29 2020, 07:55 AM
hop of those help? You can do that by materializing the even sequence:
First step: Make use of .rx extension on URLSession.shared in your network call
func networkCall(...) -> Observable<[Post]> {
    var request: URLRequest = URLRequest(url: ...)
    request.httpMethod = "..."
    request.httpBody = ...

    URLSession.shared.rx.response(request)
        .map { (response, data) -> [Post] in
            guard let json = try? JSONSerialization.jsonObject(with: data, options: []),
                let jsonDictionary = json as? [[String: Any]]
                else { throw ... }    // Throw some error here

            // Decode this dictionary and initialize your array of posts here
            ...
            return posts
        }
}
viewModel.networkCall(...)
    .materialize()
    .subscribe(onNext: { event in
        switch event {
            case .error(let error):
                // Do something with error
                break
            case .next(let posts):
                // Do something with posts
                break
            default: break
        }
    })
    .disposed(by: disposeBag)

error: Segmentation fault: 11 (in target 'RxSwift' from project 'RxSwift')


Tag : ios , By : Brandon
Date : March 29 2020, 07:55 AM
this one helps. That is for an unhandled case by Xcode and RxSwift. Project target name should not be same as library name i.e. RxSwift. Expected Xcode smart enough dealing that case with appropriate message while installing library. In my case changing project and target name to MyRxSwift fixed the issue as suggested by Karthik.
Related Posts Related QUESTIONS :
  • Can anyone explain Swift Combine's Subject.eraseToAnySubject() method and where it should be used?
  • Is there a method to blur a background in SwiftUI?
  • Getting RSA private key's n and d using Swift
  • Code=50 “No such payment_intent” when confirm payment intent for stripe
  • xcodebuild -create-framework error: unable to read the file
  • Conditional rendering with optionals in SwiftUI
  • Upgrading WKInterfaceController classes to new SwiftUI struct/View
  • TabbedView using SwiftUI in Xcode11Beta (11M336w)
  • IndexSet referring to index of the section instead of the row
  • Swift UI - How to make Image Grids?
  • Enum as a key for dictionary
  • SwiftUI - NavigationView Error message - Argument passed to call that takes no arguments
  • Does guard make a copy of variables in swift
  • Error "Argument labels '(min:, max:)' do not match any available overloads"
  • Struct Memberwise Initialization - Omitting values for properties that have defaults
  • How to get RGB components from Color SwiftUI
  • Why do Singleton's capture an instance of themselves?
  • Firebase Rules - Restrict to a specific user or only if authorized?
  • Is there a way I can combine a GeoFireStore query with a normal Firestore query?
  • SwiftUI TextField Simple Example not working
  • Initializers may only be declared within a type
  • memory leak with swift due to reference cycle
  • addUIInterruptionMonitor is not getting called on macOS
  • Show user location on map SwiftUI
  • What is the recommended logic to use when checking authenticity in Auto Renewal Subscriptions
  • Unable to deploy Swift Vapor app in gCloud
  • Project Euler Problem #2 in Swift Sum of Fibonacci Numbers Below 4 Million
  • Why return nil tableViewCell for UITableViewDiffableDataSource cellProvider param?
  • Xcode 11 beta and Mac OS Mojave: when I try to create a new project and/or open existing one it closes down with error
  • In Swift, is it a good practice to declare variables with a value assigned?
  • Deriving binding from existing SwiftUI @States
  • Advice for updating old Swift Project
  • Swift AVAssetWriter Record Video with Mic Audio AND Device Audio into a Video with ONE Audio Track AVAssetTrack
  • SwiftUI dismiss modal
  • VStack not filling screen width in ScrollView, does fill in List
  • How to detect a tap gesture location in SwiftUI?
  • Using Xcode/Swift, how can I use an SF Symbol as a tab bar icon in assets? The asset field won't accept the .svg file
  • How to fix Xcode error "Segmentation fault: 11" after adding didSet to @State var
  • Views compressed by other views in SwiftUI VStack and List
  • Why is the modifier .navigationBarTitle not applied to NavigationView?
  • "Cannot Preview in this file - Failed to launch [App Name]"
  • Get the current position of ScrollView in SwiftUI?
  • How to use buildExpression in Swift 5.2 Function Builders?
  • Where do I put a return in a function?
  • SwiftUI - Is there a popViewController equivalent in SwiftUI?
  • How to remove "row" separators from a List in SwiftUI?
  • Understanding @Binding in SwiftUI
  • Convert Realm list of Strings to Array of Strings in Swift
  • Are the #if DEBUG statements really needed for previews in SwiftUI to remove it in a release build?
  • WkWebView in MacOS remains blank on local or remote content
  • Set Toggle color in SwiftUI
  • Reduce a double in swift
  • Trouble Arranging SceneKit Nodes into a Grid
  • Combine in Playgrounds
  • Singleton class can be created without using 'Static'?
  • How do I fix this '<=' is not a prefix unary operator error?
  • What is the property / $property syntax for bindings?
  • Where should I place the process that don't have relation to UI
  • What does the attribute `@EnvironmentObject` mean in the SwiftUI?
  • Is SwiftUI backwards-compatible with iOS 12.x and older?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com