Retrofit, combined with RxAndroid, is probably the best web request framework ever. In a project, you only need one piece of code to complete the web request and callback processing. Take a look at the official Google example:
public class UserActivity extends AppCompatActivity {
// Data supply
private UserViewModel mViewModel;
// Manage releases of Subscriptions
private final CompositeDisposable mDisposable = new CompositeDisposable();
@Override
protected void onStart(a) {
super.onStart();
// Initiate a network request
mDisposable.add(mViewModel.getUserName()
.subscribeOn(Schedulers.io()) // The request runs in the IO thread
.observeOn(AndroidSchedulers.mainThread()) // Call back to the Android main thread
.subscribe(userName -> mUserName.setText(userName), // Callback listener
throwable -> Log.e(TAG, "Unable to update username", throwable)));
}
@Override
protected void onStop(a) {
super.onStop();
// Release the requestmDisposable.clear(); }}Copy the code
In the example above, all requests must be added in the CompositeDisposable to release when the Activity stops. What happens if we don’t release them? The answer is that the program crashes. Since your network request is running in an asynchronous thread IO, when the thread completes it calls back to the main thread, the Activity is found to have escaped, and the callback is subscribe(…). Can’t find an object, that affirmation don’t do ah, thread is also a little small temper.
Pain points
Programmers are “lazy” because it doesn’t look good to write code and each request has to be nested in add() parentheses. Second, it should be released when the Activity is destroyed.
Retrofit Rxandroid Adapter
Designed to address the Activity and Fragment lifecycle associated with Retrofit.
A, usage,
Use with(this) to associate the lifecycle, simplifying the release of activity.onStop ().
public class UserActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
MyService service = retrofit.create(MyService.class); // Your interface
service.getUser()
.with(this) // The association lifecycle
.subscribe(newYourObserver()); }}Copy the code
Second, the configuration
1, the instance of the Retrofit is initialized, add RxAndroidCallAdapterFactory as callback adapter.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://example.com/")
// Add the adapter
.addCallAdapterFactory(RxAndroidCallAdapterFactory.create())
.build();
Copy the code
Change your interface return value from Observable<> to AndroidObservable<>
interface MyService {
@GET("/user")
AndroidObservable<User> getUser(a);
}
Copy the code
Three, download
allprojects {
repositories {
/ /... Omit the other
maven { url 'https://jitpack.io'}}}Copy the code
dependencies {
implementation 'com.github.raedev:retrofit-rxandroid-adapter:latest.version'
}
Copy the code
AndroidObservable
Source please check open source address: https://github.com/raedev/retrofit-rxandroid-adapter.