Writing android with Kotlin: retrofit + rxjava try

Posted by jl9148 on Wed, 11 Dec 2019 01:11:15 +0100

Recently, I learned the Kotlin language recommended by Google for Android development, which was used to try to reconstruct the MVP+Retrofit+Rxjava code before. Here is my reconstructed Kotlin code

First add the compile of gradle:

dependencies {
    compile 'io.reactivex.rxjava2:rxjava:2.0.7'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
    compile 'com.jakewharton.rxbinding2:rxbinding:2.0.0'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.okhttp3:okhttp:3.5.0'

By the way, note the recent jar package problems of Android studio 3.0:

    androidTestCompile('com.android.support:support-annotations:26.1.0') {
        force = true

Then let's talk about Rxjava+retrofit development:

Step 1: create a class to receive data from the server
class BaseBean<T> {
    private var code: Int = 0//Return code
    private var msg: String? = null//Information returned
    private var data: T? = null//Data returned

    fun getCode(): Int {
        return code
     * Judge whether the request code is successful
    fun isSuccess(): Boolean {
        return this.code == GlobalContent.SUCCESS_CODE

    fun getMsg(): String? {
        return msg

    fun getData(): T? {
        return data
Step 2: create an interface to describe the network request
interface LoginService {
   fun submitLoginInfo(@Field("username") String username,@Field("password") String password):Observable<BaseBean<String>> ;
Step 3: create a Retrofit object and an instance of the network request interface

Create in Model layer

     * Create Service
    fun <T> createService(service: Class<T>): T? {


        return RetrofitFactory.getService(service)
     * Inspection parameter Service
     * @param service
     * @param <T>
    </T> */
    private fun <T> checkService(service: Class<T>?) {
        if (service == null)
            throw NullPointerException("service must not be null!")
        if (!service.isInterface)
            throw IllegalArgumentException("Class must be interface !")
        if (service.interfaces.size > 0)
            throw IllegalArgumentException("service interfaces must not extends other interface!")

     * Factory design pattern: creating a Retrofit object for a single design
object RetrofitFactory {
    var mRetrofit: Retrofit? = null

    fun <T> getService(service: Class<T>): T? {
        if(mRetrofit ==null) {
            synchronized(RetrofitFactory::class) {
                if (mRetrofit == null) {
                    mRetrofit = Retrofit.Builder().addCallAdapterFactory(RxJava2CallAdapterFactory.create())

        return mRetrofit?.create(service)
     * Model Instance of creating network request interface by layer implementation
class LoginModel:BaseModel,ILoginModel {
     var mService:LoginService = this.createService(LoginService.class);
 Override fun submitLoginInfo(String username, String password): Observable<BaseBean<String>>  {
        return mService.submitLoginInfo(username, password).compose(this.<BaseBean<String>>setThread());

Step 4: use observable < >The form encapsulates the network request and sends the network request

Create in Model layer

     * Set thread switch
    fun <T> setThread(): ObservableTransformer<T, T> {
        return ObservableTransformer { upstream ->
            upstream.subscribeOn(Schedulers.io())// Network request in IO thread
                    .observeOn(AndroidSchedulers.mainThread())//Return to the main thread to process the request result

On the Presenter layer

abstract class BasePresenter<T : IView> : IPresenter<T> {
    protected var mView: T? = null

   override fun attachView(view: T?) {
        this.mView = mView

    override fun detachView() {
        if (this.mView != null) {
            mView = null

    override fun getView(): T? {
        return this.mView

 * Using an abstract class to inherit BasePresenter to define the method connected with the Model layer, implement the interface connected with View, and call the method and callback interface in the implementation class

abstract class AbstractLoginPresenter:BasePresenter<ILoginView>{
	abstract fun submitLoginInfo(String username,String password)

Implementation class Presenter

class LoginPresenter:AbstractLoginPresenter{
	private var mModel:IloginModel? = null
	mModel = LoginModel()
	override fun submitLoginInfo(String username, String password){
			.subscribe(BaseObserver<String>() {
			override protected fun onFail(Throwable e){}
			override protected fun onSuccess(String data) {
            override fun onCodeError() {

In this way, a simple Retrofit and RxJava can be jointly used

Topics: Mobile Retrofit network Android Google