What is Traits?

A trait in Rx world is basically a wrapped Observable or handy custom made observables that help us to do the same thing as we can do with raw observable with only difference that it might take more time with raw Observable. We will discuss some of them available for RxSwift.

Single

Single are wrapped observables that will only emit one event or error. A good use would be network request where we only get a response or an error. Basically anytime we need a single event and not a stream of events we can use this trait.

Network Request Example

Here we are fetching a list of users from a network call

struct User:Codable {
	    var name:String
	}
	func getUsers() -> Single<[User]> {
	    return Single<[User]>.create { observer in
	        let request = URLRequest(url: URL(string: "http://www.json-generator.com/api/json/get/bYQWgUrEte")!)
	        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
	            do {
	                let users:[User] = try JSONDecoder().decode([User].self, from: data ?? Data())
	                observer(.success(users))

	            } catch let error {
	                observer(.error(error))
	            }
	        }
	        task.resume()

	        return Disposables.create {
	            task.cancel()
	        }
	    }
	}

	getUsers().subscribe(onSuccess:{(result) in
	    print(result)
	}) {(error) in
	    print(error)
	}

#rxswift #ios #ios-apps #swift #ios-app-development

How to use RxSwift Traits
8.80 GEEK