Search code examples
javascriptreactjsreact-nativerxjsfrp

Performs operations on some observables on trigger observables - RxJS


I am still trying to wrap my head around using RxJS along with React Native. I am building a login screen with a id TextInput, a password TextInput and a sign in button who all have a separate callback handler attached to them via jsx (hence I can't create an observable using 'fromEvent' API of RxJS).

In componentWillMount, I create a subject for id text change, password text change and the click handler.

//In id text change handler
this.idStream.onNext(newId);

//In password text change handler
this.passwordStream.onNext(newPassword);

//In click handler
this.buttonClickStream.onNext(null); //null since value is not important

I only want an API request to fire when the button id and password is not an empty string and the button is clicked.

In componentWillMount I tried

var subscription = this.buttonClickStream
                       .combineLatest(this.idStream, this.passwordStream, function(click, id, password) {
    return {
         id: id,
         password: password
    };
})
.filter(credentials => {return credentials.id.length > 0 &&
                               credentials.password.length > 0;}
.subscribe(function(credentials) {
    console.log('fire API request with credentials');
});

However the problem with this is, since I'm using combineLatest, the api is fired not just on the button click but also every time I change the id or password (provided that they pass the filter). What am I missing?

Thanks!


Solution

  • I think you could use Rx.withLatestFrom instead of combineLatest. It fires only when the source observable fires and take the last emitted values of the observables you pass as parameter.

    Cf. http://rxmarbles.com/#withLatestFrom