How to use RxSwift Traits

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



let singleOne = Single<String>.just("I am a single event emitter")
singleOne.subscribe(onSuccess:{(result) in
print(result)
}) {(error) in
print(error)
}

Output

I am a single event emitter

Completable

This variation of observable can only get completed or emit an error. This doesn’t emit any elements. It will only give us a completed event or error. This could be perfect for scenario where we just want to make sure a task/operation gets done without error and we don’t need anything from it.

A good use case would be if you are saving in database or say uploading a file to server, where you only care about task getting done without error.

let comp = Completable.empty()comp.subscribe(onCompleted:{    print("completed")}) {(error) in    print(error)}

Output

completed

References

https://github.com/ReactiveX/RxSwift/blob/master/Documentation/Traits.md

Popular posts from this blog

How to make an iOS App Secure?

System Design Interview For Mobile Engineers

How to make iOS app secure from screenshot and recording?