mvvm框架 android,android mvvm架构

# android mvvm demo# 仓库地址: https://github.com/lzyprime/android_demos# branch: mvvmgit clone -b mvvm https://github.com/lzyprime/android_demos

添加组件

网络:Retrofit + kotlin 协程

我也试过其他框架:Fuel, Ktor Client。但是迫于业务需求,最后保留了Retrofit。如果网络请求比较简单,可以试试这两个框架,由kotlin实现,和协程配合更好。

lifecycle ktx:ViewModel, LiveData

androidx.lifecycle:lifecycle-runtime-ktx

androidx.lifecycle:lifecycle-livedata-ktx

androidx.lifecycle:lifecycle-viewmodel-ktx

androidx.activity:activity-ktx

其中activity-ktx目的:

classMyActivity:AppCompatActivity(){overridefunonCreate(savedInstanceState:Bundle?){// Create a ViewModel the first time the system calls an activity's onCreate() method.// Re-created activities receive the same MyViewModel instance created by the first activity.// Use the 'by viewModels()' Kotlin property delegate// from the activity-ktx artifactvalmodel:MyViewModelbyviewModels()model.getUsers().observe(this,Observer>{users->// update UI})}}

依赖注入:Hlit

数据库:Room

Room (暂时没需求)

MVVM

0. init

NetUtil

// 网络请求工具// utils/Net.ktobjectNet{privateconstvalPROP_BASE_URL="https://api.unsplash.com/"privateconstvalDEBUG_BASE_URL="https://api.unsplash.com/"privatevalBASE_URLget()=DEBUG_BASE_URLprivateconstvalACCESS_KEY=""// 注册https://api.unsplash.com/后拿到valretrofit:Retrofitbylazy{valokHttpClient=OkHttpClient.Builder().addInterceptor{chain->valurl=chain.request().url().newBuilder().addQueryParameter("client_id",ACCESS_KEY).build()valrequest=chain.request().newBuilder().url(url).build()chain.proceed(request)}.build()Retrofit.Builder().baseUrl(BASE_URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build()}}

Response

// 处理网络回包// data/bean/Response.ktsealedclassResponse{dataclassSuccess(valdata:T):Response()objectFailed:Response()}

Application

// 依赖注入// UnsplashApplication.kt@HiltAndroidAppclassUnsplashApplication:Application(){...}

...

1. Model

data bean

// json 解析,变量名与json字段一致// data/bean/Photo.ktdataclassPhoto(valid:String,valcreated_at:String="",valupdated_at:String="",valurls:Urls,vallikes:Long=0,valliked_by_user:Boolean=false,valuser:User,){dataclassUrls(valraw:String,valfull:String,valregular:String,valsmall:String,valthumb:String,)}// data/bean/User.ktdataclassUser(valid:String,valupdated_at:String="",valusername:String="",valname:String="",valfirst_name:String="",vallast_name:String="",)

retrofit interface

// retrofit 请求interface// data/api/UnsplashService.ktinterfaceUnsplashService{@GET("photos")suspendfunlistPhotos():List}

service module

// hilt 依赖注入,interface无法直接构造,需要通过Module和Provides指明构造方式// data/api/ServiceModule.kt@Module@InstallIn(ApplicationComponent::class)objectServiceModule{privateinlinefuncreateService():T=Net.retrofit.create(T::class.java)@Singleton@ProvidesfununsplashService():UnsplashService=createService()}

Model: UnsplashRepository

// model层,提供数据// data/UnsplashRepository.kt@SingletonclassUnsplashRepository@Injectconstructor(privatevalservice:UnsplashService){suspendfunlistPhoto()=try{Response.Success(service.listPhotos())}catch(_:Exception){Response.Failed}}

2. ViewModel

//viewmodels/ListPhotoViewModel.ktclassListPhotoViewModel@ViewModelInjectconstructor(privatevalrepository:UnsplashRepository):ViewModel(){vallistPhotos:MutableLiveData>=MutableLiveData()funrefreshListPhotos()=viewModelScope.launch{when(valres=repository.listPhoto()){isResponse.Success->listPhotos.value=res.dataisResponse.Failed->listPhotos.value=emptyList()}}}

3. View

// RecycleView, RefreshBottun, 暴力写法// MainActivity.kt@AndroidEntryPointclassMainActivity:AppCompatActivity(){privatevalmodel:ListPhotoViewModelbyviewModels()init{lifecycleScope.launchWhenCreated{model.refreshListPhotos()}}overridefunonCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)refreshBtn.setOnClickListener{model.refreshListPhotos()}photoList.layoutManager=GridLayoutManager(this,2)model.listPhotos.observe(this){photos->photoList.adapter=object:RecyclerView.Adapter(){overridefunonCreateViewHolder(parent:ViewGroup,viewType:Int):RecyclerView.ViewHolder=object:RecyclerView.ViewHolder(ImageView(parent.context)){}overridefunonBindViewHolder(holder:RecyclerView.ViewHolder,position:Int){valphoto=photos[position]with(holder.itemViewasImageView){Glide.with(this).load(photo.urls.raw).into(this)}}overridefungetItemCount():Int=photos.size}}}}

1人点赞

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值