CombineLatest and withLatestFrom in RxSwift

Tram Ho

Hello everyone, in today’s article I will write about 2 commonly used operators when RxSwift code is combineLatest and withLatestFrom .

I often confuse these 2 operators because they keep the same

In this article, I will show how they are different, and how to use them.

I will create a simple Login screen, including an email entry form, a password entry form, and a login button (disabled initially) as follows:

1. CombineLatest

CombineLatest is simply to merge 2 or more obseverable and emit out when one of the observerable sources with a new value is updated.

Here is the diagram for you to better understand:

Please explain a little bit of this diagram:

  • The first 2 horizontal arrows are 2 observerable sources, when using operator combineLatest, create 1 observerable as the bottom arrow.
  • Every time there is a new event from 1 of the 2 observerable sources, we will get the latest value from the combined sources.

I will example on the Login screen I just created: at first the Login button will be disabled, it is enabled when both email form and password are input.

The following results:

Now, I want when the Login button is enabled, pressing the login button will send this set of emails and passwords to the server. As we know above, every time we change the input value of email or password we will generate a new event, which means that if we use combineLatest for the event login (in this example loginButton.rx.tap will be triggered a lot of times, this is something we did not want, withLatestFrom will help us to solve this problem.

2. WithLatestFrom

Here is the diagram of withLatestFrom:

And this is my example, the purpose is when pressing the login button will print the entered value of the email and password (connect to the code above):

I explain the diagram associated with my code:

  • The first horizontal arrow is observerable indicating the click on Login button, the second horizontal arrow is the value of email and password.
  • Using withLatestFrom will create an observerable which is the bottom arrow, it will only signal (emit) when the Login button is pressed.
  • When I change the email or password, it still hasn’t signaled because the Login button has not been pressed.

Now let’s see the results together. (pay attention to the log):

Hope you guys understand these 2 operators, thanks for reading the article

Share the news now

Source : Viblo