学习笔记Kotlin+MVP+Retrofit登陆案例

文章目录

    • 1、接口协议
    • 2、视图层
    • 3、数据层
    • 4、提供者
    • 一些拓展函数
    • Retofit

先看一下包结构
学习笔记Kotlin+MVP+Retrofit登陆案例_第1张图片

1、接口协议

按照需求先定义一下各层的接口

interface LoginContract {
    interface Presenter {

        fun login(username: String, password: String)
    }

    interface View {

        fun onUsernameError()

        fun onPasswordError()

        fun onLoginSuccess()

        fun onLoginFalied(msg:String)

    }

    interface Model {
        fun login(username: String, password: String, loginCallback: LoginCallback)

        interface LoginCallback {

            fun onSuccess(user: User)

            fun onError(error: String)
        }
    }
}

2、视图层

在activity中实现View层接口

class LoginActivity : BaseActivity(), LoginContract.View {
    private val presenter = LoginPresenter(this)

    override fun getLayoutId(): Int = R.layout.activity_login

    override fun init() {
        super.init()
        et_username.setText("admin")
        et_password.setText("123456")
        btn_login.setOnClickListener {
            login()
        }
        btn_register.setOnClickListener { startActivity<RegisterActivity>() }
        et_password.setOnEditorActionListener { _, _, _ ->
            login()
            true
        }
    }

    private fun login() {
        showProgress("正在登陆...")
        presenter.login(et_username.text.toString(), et_password.text.toString())
    }

    override fun onLoginSuccess() {
        closeProgress()
        toast("登录成功!", true)
        startActivity<MainActivity>()
        finish()
    }

    override fun onUsernameError() {
        closeProgress()
        et_username.error = "账号不合法!"
    }

    override fun onPasswordError() {
        closeProgress()
        et_password.error = "密码不合法!"
    }

    override fun onLoginFalied(msg: String) {
        closeProgress()
        toast(msg, false)
    }
}

我的BaseActivity,酌情取用

abstract class BaseActivity : AppCompatActivity() {

    private val progressDialog by lazy {
        ProgressDialog(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getLayoutId())
        init()
    }

    open fun init() {

    }

    abstract fun getLayoutId(): Int

    fun showProgress(msg: String) {
        progressDialog.message(text = msg)
        progressDialog.show()
    }

    fun closeProgress() {
        progressDialog.dismiss()
    }

    fun toast(msg: String, type: Boolean) {
        if (type) {
            Toasty.success(this, msg).show()
        } else {
            Toasty.error(this, msg).show()
        }
    }
}

3、数据层

是一个object

object LoginModel : LoginContract.Model {
    override fun login(username: String, password: String, loginCallback: LoginContract.Model.LoginCallback) {
        val request = JSONObject()
        request.put("userAccount", username)
        request.put("password", password)
        NetClient.create().login(request.toRequest())
            .enqueue(object : Callback<MyResponse2<User>> {
                override fun onFailure(call: Call<MyResponse2<User>>, t: Throwable) {
                    loginCallback.onError("网络出现问题!")
                    Log.d("myNet", "Msg:" + t.message + ", Cause:" + t.cause)
                }

                override fun onResponse(call: Call<MyResponse2<User>>, response: Response<MyResponse2<User>>) {
                    response.body()?.let {
                        if (it.status == 1) {
                            loginCallback.onSuccess(it.data)
                        } else loginCallback.onError(it.message!!)
                    }
                }
            })
    }
}

4、提供者

class LoginPresenter(var view: LoginContract.View) : LoginContract.Presenter {

    override fun login(username: String, password: String) {
        if (username.isValidUserName()) {
            if (password.isValidPassword()) {
                LoginModel.login(username, password, object : LoginContract.Model.LoginCallback {
                    override fun onSuccess(user: User?) {
                        view.onLoginSuccess()
                        Hawk.put("User", user)
                    }

                    override fun onError(error: String) {
                        view.onLoginFalied(error)
                    }
                })
            } else view.onPasswordError()
        } else view.onUsernameError()
    }
}

一些拓展函数

按需求改改正则表达式

fun String.isValidUserName(): Boolean = this.matches(Regex("^[A-Za-z0-9]{4,20}\$"))

fun String.isValidPassword(): Boolean = this.matches(Regex("^[A-Za-z0-9]{4,20}\$"))

Retofit

这里写图片描述

先加一下依赖

    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'

定义一下访问接口,都可以放在这里统一管理

interface NetService {
    //登录
    @POST("user/login")
    fun login(@Body body: RequestBody): Call<MyResponse<User>>
    
    ...其它接口
}

最后写个 Client
采用了 object 实现单例

object NetClient {

    private val service: NetService

    init {
        val loggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }

        val client = OkHttpClient.Builder().apply {
            addInterceptor(loggingInterceptor)
            connectTimeout(15, TimeUnit.SECONDS)
            readTimeout(15, TimeUnit.SECONDS)
            writeTimeout(15, TimeUnit.SECONDS)
            retryOnConnectionFailure(true)
        }.build()

        service = Retrofit.Builder()
            .baseUrl("http://192.168.1.66:7878/")
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build()
            .create(NetService::class.java)
    }

    fun create(): NetService {
        return service
    }
}

然后就可以在model里调用啦~( ̄▽ ̄~),见上方model部分(^ _ ^)/~~

你可能感兴趣的:(学习笔记)