-
Notifications
You must be signed in to change notification settings - Fork 3
RxJava simple explanation
First, I will explain line-by-line what is happening.
We will be using a generic signIn() method.
public void signIn() {
BiAffectBridge instance = BiAffectBridge.getInstance();
Single<UserSessionInfo> signInApiCall = instance.signIn( "email", "password" );
signInApiCall.subscribe( new OnSignInSuccess(), new OnSignInError() );
}BiAffectBridge instance = BiAffectBridge.getInstance();
Here, we get the BiAffectBridge instance.
Single<UserSessionInfo> signInApiCall = instance.signIn( "email", "password" );
In this line, we are calling instance.signIn() with an email and password.
This returns a Single<UserSessionInfo> object that we name signInApiCall.
A Single is a type of Observable, which means that it has data that can be "observed".
In this case, the data that we are observing is a UserSessionInfo object.
In other words, it's like the return value of the API call.
If this wasn't a threaded network call, it might look like this:
UserSessionInfo result = instance.signIn();
The Single just wraps the entire network call in a multi-threaded manner.
In order to receive the UserSessionInfo result object, something needs to receive it.
We refer to this "something" as the subscriber.
You will need to create the subscriber.
This subscriber essentially just tells RxJava what to do with the UserSessionInfo object.
A Single can have only one of two results: success, or error.
Therefore, our subscriber will need to handle both of them.
Going back to our previous example, if this was not a threaded network call, it might look like this:
UserSessionInfo result = instance.signIn();
if( result.success ) {
Log.d( "success! move on to the next screen" );
} else {
Log.d( "error, show a dialog to the user" );
}The way we do this is by creating two classes that can handle the two results.
signInApiCall.subscribe( new OnSignInSuccess(), new OnSignInError() );
One final note, logically, we can't start the API call unless there's something that can receive the results.
Therefore, the actual HTTP call doesn't happen until .subscribe() is called.
private class OnSignInSuccess implements Action1<UserSessionInfo> {
@Override
public void call( UserSessionInfo userSessionInfo ) {
Log.d( "success! move on to the next screen" );
}
}
private class OnSignInError implements Action1<Throwable> {
@Override
public void call( Throwable throwable ) {
Log.d( "error, show a dialog to the user" );
}
}Now that you have a basic understanding of what is going on, we can take advantage of method chaining and lambda notation in order to make this shorter and less verbose.
public void signIn() {
BiAffectBridge.getInstance()
.signIn( "email", "password" )
.subscribe(
userSessionInfo -> {
Log.d( "success! move on to the next screen" );
}, throwable -> {
Log.d( "error, show a dialog to the user" );
} );
}