Android 架构实战MVI进阶

news2024/9/22 23:38:30

MVI架构的原理和流程

MVI架构是一种基于响应式编程的架构模式,它将应用程序分为四个核心组件:模型(Model)、视图(View)、意图(Intent)和状态(State)。 原理:

  • 模型(Model):负责处理数据的状态和逻辑。
  • 视图(View):负责展示数据和用户界面。
  • 意图(Intent):代表用户的操作,如按钮点击、输入等。
  • 状态(State):反映应用程序的当前状态。

流程:

  1. 用户通过视图(View)发起意图(Intent)。
  2. 意图(Intent)被传递给模型(Model)。
  3. 模型(Model)根据意图(Intent)进行状态(State)的更新。
  4. 状态(State)的变化被传递给视图(View),视图(View)进行相应的界面更新。

优点:

  • 单向数据流:通过单向的数据流动,可确保状态的一致性和可预测性。
  • 响应式特性:MVI利用响应式编程的思想,实现了对状态变化的高效处理。
  • 易于测试:由于数据流的清晰性,测试模型的行为变得更加容易。

缺点:

  • 学习曲线较陡:相对于传统的MVC或MVP,MVI架构需要开发者熟悉响应式编程的概念和工具。
  • 增加了一些复杂性:引入状态管理和数据流管理,可能会增加一定的复杂性。

单向数据流

用户操作以Intent的形式通知Model => Model基于Intent更新State => View接收到State变化刷新UI。数据永远在一个环形结构中单向流动,不能反向流动:

一个Sample快速搭建一个MVI架构的项目

代码示例

代码结构如下:

Sample中的依赖库

// Added Dependencies
implementation "androidx.recyclerview:recyclerview:1.1.0"
implementation 'android.arch.lifecycle:extensions:1.1.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0'
implementation 'com.github.bumptech.glide:glide:4.11.0'

//retrofit
implementation 'com.squareup.retrofit2:retrofit:2.8.1'
implementation "com.squareup.retrofit2:converter-moshi:2.6.2"

//Coroutine
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.6"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.6"

代码中使用以下API进行请求

https://reqres.in/api/users

将得到结果:

1. 数据层

1.1 User

定义User的data class

package com.my.mvi.data.model

data class User(
    @Json(name = "id")
    val id: Int = 0,
    @Json(name = "first_name")
    val name: String = "",
    @Json(name = "email")
    val email: String = "",
    @Json(name = "avator")
    val avator: String = ""
)

1.2 ApiService

定义ApiService,getUsers方法进行数据请求

package com.my.mvi.data.api

interface ApiService {

   @GET("users")
   suspend fun getUsers(): List<User>
}

1.3 Retrofit

创建Retrofit实例

object RetrofitBuilder {

    private const val BASE_URL = "https://reqres.in/api/user/1"

    private fun getRetrofit() = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(MoshiConverterFactory.create())
        .build()


    val apiService: ApiService = getRetrofit().create(ApiService::class.java)

}

1.4 Repository

定义Repository,封装API请求的具体实现

package com.my.mvi.data.repository

class MainRepository(private val apiService: ApiService) {

    suspend fun getUsers() = apiService.getUsers()

}

2. UI层

Model定义完毕后,开始定义UI层,包括View、ViewModel以及Intent的定义

2.1 RecyclerView.Adapter

首先,需要一个RecyclerView来呈现列表结果,定义MainAdapter如下:

package com.my.mvi.ui.main.adapter

class MainAdapter(
    private val users: ArrayList<User>
) : RecyclerView.Adapter<MainAdapter.DataViewHolder>() {

    class DataViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(user: User) {
            itemView.textViewUserName.text = user.name
            itemView.textViewUserEmail.text = user.email
            Glide.with(itemView.imageViewAvatar.context)
                .load(user.avatar)
                .into(itemView.imageViewAvatar)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        DataViewHolder(
            LayoutInflater.from(parent.context).inflate(
                R.layout.item_layout, parent,
                false
            )
        )

    override fun getItemCount(): Int = users.size

    override fun onBindViewHolder(holder: DataViewHolder, position: Int) =
        holder.bind(users[position])

    fun addData(list: List<User>) {
        users.addAll(list)
    }

}

item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="60dp">

    <ImageView
        android:id="@+id/imageViewAvatar"
        android:layout_width="60dp"
        android:layout_height="0dp"
        android:padding="4dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/textViewUserName"
        style="@style/TextAppearance.AppCompat.Large"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="4dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/imageViewAvatar"
        app:layout_constraintTop_toTopOf="parent"/>

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/textViewUserEmail"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/textViewUserName"
        app:layout_constraintTop_toBottomOf="@+id/textViewUserName" />

</androidx.constraintlayout.widget.ConstraintLayout>

2.2 Intent

定义Intent用来包装用户Action

package com.my.mvi.ui.main.intent

sealed class MainIntent {

    object FetchUser : MainIntent()

}

2.3 State

定义UI层的State结构体

sealed class MainState {

    object Idle : MainState()
    object Loading : MainState()
    data class Users(val user: List<User>) : MainState()
    data class Error(val error: String?) : MainState()

}

2.4 ViewModel

ViewModel是MVI的核心,存放和管理State,同时接受Intent并进行数据请求

package com.my.mvi.ui.main.viewmodel

class MainViewModel(
    private val repository: MainRepository
) : ViewModel() {

    val userIntent = Channel<MainIntent>(Channel.UNLIMITED)
    private val _state = MutableStateFlow<MainState>(MainState.Idle)
    val state: StateFlow<MainState>
        get() = _state

    init {
        handleIntent()
    }

    private fun handleIntent() {
        viewModelScope.launch {
            userIntent.consumeAsFlow().collect {
                when (it) {
                    is MainIntent.FetchUser -> fetchUser()
                }
            }
        }
    }

    private fun fetchUser() {
        viewModelScope.launch {
            _state.value = MainState.Loading
            _state.value = try {
                MainState.Users(repository.getUsers())
            } catch (e: Exception) {
                MainState.Error(e.localizedMessage)
            }
        }
    }
}

我们在handleIntent中订阅userIntent并根据Action类型执行相应操作。本case中当出现FetchUser的Action时,调用fetchUser方法请求用户数据。用户数据返回后,会更新State,MainActivity订阅此State并刷新界面。

2.5 ViewModelFactory

构造ViewModel需要Repository,所以通过ViewModelFactory注入必要的依赖

class ViewModelFactory(private val apiService: ApiService) : ViewModelProvider.Factory {

    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
            return MainViewModel(MainRepository(apiService)) as T
        }
        throw IllegalArgumentException("Unknown class name")
    }

}

2.6 定义MainActivity

package com.my.mvi.ui.main.view

class MainActivity : AppCompatActivity() {

    private lateinit var mainViewModel: MainViewModel
    private var adapter = MainAdapter(arrayListOf())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setupUI()
        setupViewModel()
        observeViewModel()
        setupClicks()
    }

    private fun setupClicks() {
        buttonFetchUser.setOnClickListener {
            lifecycleScope.launch {
                mainViewModel.userIntent.send(MainIntent.FetchUser)
            }
        }
    }


    private fun setupUI() {
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.run {
            addItemDecoration(
                DividerItemDecoration(
                    recyclerView.context,
                    (recyclerView.layoutManager as LinearLayoutManager).orientation
                )
            )
        }
        recyclerView.adapter = adapter
    }


    private fun setupViewModel() {
        mainViewModel = ViewModelProviders.of(
            this,
            ViewModelFactory(
                ApiHelperImpl(
                    RetrofitBuilder.apiService
                )
            )
        ).get(MainViewModel::class.java)
    }

    private fun observeViewModel() {
        lifecycleScope.launch {
            mainViewModel.state.collect {
                when (it) {
                    is MainState.Idle -> {

                    }
                    is MainState.Loading -> {
                        buttonFetchUser.visibility = View.GONE
                        progressBar.visibility = View.VISIBLE
                    }

                    is MainState.Users -> {
                        progressBar.visibility = View.GONE
                        buttonFetchUser.visibility = View.GONE
                        renderList(it.user)
                    }
                    is MainState.Error -> {
                        progressBar.visibility = View.GONE
                        buttonFetchUser.visibility = View.VISIBLE
                        Toast.makeText(this@MainActivity, it.error, Toast.LENGTH_LONG).show()
                    }
                }
            }
        }
    }

    private fun renderList(users: List<User>) {
        recyclerView.visibility = View.VISIBLE
        users.let { listOfUsers -> listOfUsers.let { adapter.addData(it) } }
        adapter.notifyDataSetChanged()
    }
}

MainActivity中订阅mainViewModel.state,根据State处理各种UI显示和刷新。

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.main.view.MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" />

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:visibility="gone"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/buttonFetchUser"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/fetch_user"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

如上,一个完整的MVI项目完成了。

实战讲解和代码示例

为了更好地理解MVI架构,让我们通过一个例子进行实战演示。我们将创建一个天气预报应用,展示当前天气和未来几天的天气预报信息。 在代码示例中,我们会用到以下库:

  • RxJava:用于处理响应式数据流。
  • LiveData:用于将数据流连接到视图。
 首先,我们定义模型(Model)的状态(State)类,包含天气预报的相关信息,例如温度、湿度和天气状况等。
data class WeatherState(
    val temperature: Float,
    val humidity: Float,
    val condition: String
)

接下来,我们创建视图(View)界面,展示天气信息,并提供一个按钮用于刷新数据。


class WeatherActivity : AppCompatActivity() {

    // 初始化ViewModel
    private val viewModel: WeatherViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_weather)

        // 监听状态变化,更新UI
        viewModel.weatherState.observe(this, Observer { state ->
            // 更新温度、湿度和天气状况的显示
            temperatureTextView.text = state.temperature.toString()
            humidityTextView.text = state.humidity.toString()
            conditionTextView.text = state.condition
        })

        // 刷新按钮点击事件
        refreshButton.setOnClickListener {
            // 发送刷新数据的意图
            viewModel.processIntent(RefreshIntent)
        }
    }
}

然后,我们创建意图(Intent)类,代表用户操作的动作。在这个例子中,我们只有一个刷新数据的意图。


object RefreshIntent : WeatherIntent

接下来,我们实现模型(Model)部分,包括状态管理和数据流的处理。


class WeatherViewModel : ViewModel() {

    // 状态管理
    private val _weatherState = MutableLiveData<WeatherState>()
    val weatherState: LiveData<WeatherState> = _weatherState

    // 处理意图
    fun processIntent(intent: WeatherIntent) {
        when (intent) {
            RefreshIntent -> fetchWeatherData()
        }
    }

    // 获取天气数据
    private fun fetchWeatherData() {
        // 发起网络请求或其他数据获取逻辑
        // 更新状态
        val weatherData = // 获取的天气数据
        val newState = WeatherState(
            temperature = weatherData.temperature,
            humidity = weatherData.humidity,
            condition = weatherData.condition
        )
        _weatherState.value = newState
    }
}

全文对Android中MVI的架构讲解,其中包括原理、项目演示以及实战演练。有关更多的Android架构学习进阶可以参考《Android核心技术手册》文档,点击可以查看详细的内容板块。

总结

MVI架构通过响应式数据流和单向数据流的特性,提供了一种可维护、可测试且具备响应式特性的架构模式。尽管学习曲线较陡,但在大型复杂应用开发中,MVI架构能够更好地管理状态和响应用户操作。通过合理设计状态模型和注意副作用管理,我们可以充分发挥MVI架构的优势,提升应用的可维护性和用户体验。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1272837.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Mybatisplus同时向两张表里插入数据[事务的一致性]

一、需求&#xff1a;把靶器官的数据&#xff0c;单独拿出来作为一个从表&#xff0c;以List的方式接收这段数据&#xff1b; 此时分析&#xff0c;是需要有两个实体的&#xff0c;一个是主表的实体&#xff0c;一个是从表的实体&#xff0c;并在主表实体新增一个List 字段来接…

免费WordPress站群插件-批量管理站群的免费软件

WordPress站群插件&#xff1a;让文章管理如丝般顺滑 在众多网站建设工具中&#xff0c;WordPress一直以其简便易用、丰富的插件生态而备受青睐。对于站群管理者而言&#xff0c;如何高效地更新、发布和推送文章是一项不可忽视的任务。本文将专注分享一款WordPress站群插件&am…

Rust的Vec优化

本篇是对Rust编程语言17_Rust的Vec优化[1]学习与记录 MiniVec https://crates.io/crates/minivec enum DataWithVec { // tag,uint64,8字节 I32(i32), // 4字节,但需内存对齐到8字节? F64(f64), // 8字节 Bytes(Vec<u8>), // 24字节}fn main()…

watch函数与watchEffect函数

watach函数&#xff1a; 与vue2.x的配置功能一致 监视指定的一个或多个响应式数据, 一旦数据变化, 就自动执行监视回调 默认初始时不执行回调, 但可以通过配置immediate为true, 来指定初始时立即执行第一次 通过配置deep为true, 来指定深度监视 watchEffect函数&#xff1a;…

电商项目之Web实时消息推送(附源码)

文章目录 1 问题背景2 前言3 什么是消息推送4 短轮询5 长轮询5.1 demo代码 6 iframe流6.1 demo代码 7 SSE7.1 demo代码7.2 生产环境的应用 &#xff08;重要&#xff09; 8 MQTT 1 问题背景 扩宽自己的知识广度&#xff0c;研究一下web实时消息推送 2 前言 文章参考自Web 实时消…

什么是PDN的交流阻抗?

什么是PDN的交流阻抗&#xff1f; 在电力电子领域&#xff0c;PDN&#xff08;Power Distribution Network&#xff09;的交流阻抗是一个重要的概念&#xff0c;它反映了PDN在交流电源和负载之间传输电能的能力。了解PDN的交流阻抗对于优化电源设计、提高系统性能和可靠性具有重…

js提取iconfont项目的图标

iconfont 可以让我们轻松使用字体图标&#xff0c;比如使用 iconfont 提供的 js&#xff0c;就可以愉快的码代码了。 //at.alicdn.com/t/c/font_xxxxx.js通常公司会有提供一套图标供所有系统使用&#xff0c;比如图标库里有 1000 个图标&#xff0c;但某个项目只需要使用 10 个…

AI生成的图片有版权了

我是卢松松&#xff0c;点点上面的头像&#xff0c;欢迎关注我哦&#xff01; 把发到小红书的AI图片搬运到百家号&#xff0c;然后被起诉了! 长知识了&#xff0c;原来AI生成的图片也有版权了&#xff0c;AI生成图片著作权第一案判了&#xff0c;这绝对是一件划时代事情&…

Linux常用命令----mkdir命令

文章目录 1. 基础概念2. 参数含义3. 常见用法4. 实例演示5. 结论 在Linux操作系统中&#xff0c;mkdir 命令是用来创建目录的基础命令。这个命令简单但极其强大&#xff0c;是每个Linux用户都应当熟悉的工具之一。以下是对mkdir命令的详细介绍&#xff0c;包括其参数含义、常见…

免费版的水淼采集器下载-水淼采集器详细使用教程

在当今信息爆炸的时代&#xff0c;网络上的数据量庞大&#xff0c;如何高效地采集、整理并利用这些信息成为了许多人关注的问题。水淼采集器作为一种强大的免费工具&#xff0c;在信息搜集的领域扮演着举足轻重的角色。本文将深入探讨水淼采集器的使用以及提供一份简明易懂的教…

广州华锐视点:VR禁毒安全体验馆:珍爱生命,远离毒品!

随着科技的不断发展&#xff0c;虚拟现实&#xff08;VR&#xff09;技术已经逐渐走进我们的生活。从游戏娱乐到医疗教育&#xff0c;VR技术的应用范围日益广泛。近年来&#xff0c;VR技术在禁毒教育领域的应用也取得了显著的成果&#xff0c;为提高人们的禁毒意识和防范能力提…

1+x中级网络运维实验题

任务 1&#xff1a; 设备命名 为了方便后期维护和故障定位及网络的规范性&#xff0c;需要对网络设备进行规范化命名。请根据 Figure 3-1 实验考试拓扑对设备进行命名。命名规则为&#xff1a;城市-设备的设置地点-设备的功能属性和序号-设备型号。例如&#xff1a;处于杭州校…

v-on: 事件处理简写@,及修饰符

v-on 是 Vue中用于绑定事件的指令。它可以绑定许多不同的事件&#xff0c;如&#xff1a; click&#xff1a;鼠标点击事件input&#xff1a;输入框内容变化事件keydown&#xff1a;按键按下事件keyup&#xff1a;按键松开事件submit&#xff1a;表单提交事件mouseover&#xf…

「Bomkus 博士的试炼」排行榜规则更新

亲爱的玩家们 为了回应我们从社区收到的宝贵反馈&#xff0c;我们希望与大家分享我们为防止在「Bomkus 博士的试炼」排行榜中作弊而采取的措施的最新进展&#xff0c;并就这一主题提供更多说明。 除了在活动开始前采取的反作弊措施外&#xff0c;我们还根据观察到的和报告的行为…

新金融时代、AMCAP谱写财富梦想新篇章

近年来&#xff0c;智能配置投资与理财逐渐受到关注并走俏。这是一种简单快捷的智慧化理财方式&#xff0c;通过将个人和家族的闲置资金投入到低风险高流动性的产品中。 国际财富管理投资机构AMCAP集团金融分析师表示&#xff1a;智能配置投资与理财之所以持续走俏&#xff0c…

KMP基础架构

前言 Kotlin可以用来开发全栈, 我们所熟悉的各个端几乎都支持(除了鸿蒙) 而我们要开发好KMP项目需要一个好的基础架构,这样不仅代码更清晰,而且能共享更多的代码 正文 我们可以先将KMP分为前端和服务端 它们两端也能共享一些代码,比如接口声明,bean类,基础工具类等 前端和…

基于SpringBoot学生读书笔记共享

摘 要 本论文主要论述了如何使用JAVA语言开发一个读书笔记共享平台 &#xff0c;本系统将严格按照软件开发流程进行各个阶段的工作&#xff0c;采用B/S架构&#xff0c;面向对象编程思想进行项目开发。在引言中&#xff0c;作者将论述读书笔记共享平台的当前背景以及系统开发的…

5 存储器映射和寄存器

文章目录 5.3 芯片内核5.3.1 ICache5.3.2 DCache5.3.3 FlexRAM 5.4 存储器映射5.4.1 存储器功能划分5.4.1.1 存储器 Block0 内部区域功能划分5.4.1.2 储存器 Block1 内部区域功能划分5.4.1.3 储存器 Block2 内部区域功能划分 5.5 寄存器映射5.5.1 GPIO1的输出数据寄存器 5.3 芯…

上海线下活动 | LLM 时代的 AI 编译器实践与创新

今年 3 月份&#xff0c; 2023 Meet TVM 系列首次线下活动从上海出发&#xff0c;跨越多个城市&#xff0c;致力于为各地关注 AI 编译器的工程师提供一个学习、交流的平台。 12 月 16 日 2023 Meet TVM 年终聚会将重返上海&#xff0c;这一次我们不仅邀请了 4 位资深的 AI 编…

2021年6月3日 Go生态洞察:Fuzzing技术的Beta测试

&#x1f337;&#x1f341; 博主猫头虎&#xff08;&#x1f405;&#x1f43e;&#xff09;带您 Go to New World✨&#x1f341; &#x1f984; 博客首页——&#x1f405;&#x1f43e;猫头虎的博客&#x1f390; &#x1f433; 《面试题大全专栏》 &#x1f995; 文章图文…