Reputation: 1460
I have just started learning how to use RxJava 2 and Retrofit 2 in Android. I have followed a number of tutorials and I am able to retrieve data from my server. My question is, what is the standard way to easily access that retrieved data. Currently GSON parses it into an object, I print the toString, but that is it.
I have this interface to define my POST request:
public interface FacebookAppLoginService {
@POST("app/fbapp_login")
Observable<User> getUser(@Body FacebookAccessToken facebookAccessToken);
}
I create the Retrofit object:
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("http://rocky-garden-56471.herokuapp.com/")
.build();
I then create an object to contain the JSON body of my POST request:
FacebookAccessToken facebookAccessToken = new FacebookAccessToken();
I then create the Observable from my interface:
Observable<User> newUser = facebookAppLoginService.getUser(facebookAccessToken);
Finally, I subscribe to the observable, observing on the main thread, but doing the request on a worker thread (I think), then I log the results:
newUser.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(userInfo -> {
Log.i("Server Call", "Received: " + userInfo.toString());
});
The toString correctly prints out the user information received from the server. What is the standard way to use this object that I get in the lambda function? I would like to store it in the database, or at the least save it in a Object within the activity. How should I go about doing this?
Upvotes: 0
Views: 1242
Reputation: 734
Your interpretation of what happens threadwise is correct. You are doing the request on a new thread and the lambda in subscribe() will be called on the UI-thread
You can just write the rest of the code in the lambda function. You can access the surrounding class and store it in a field there or access a database class/method from there. Note that you only need to observe on the main thread if you want to access ui here. If you just want to save it you can remove the observeOn() call and stay on the background thread. Also I would recommend using Schedulers.io() for the subscribeOn() because it is a threadpool meant for io operations including network operations and database access .
Upvotes: 1