android mvi开发模式,kotlin - android MVI architecture retrieving 'by observer' - Stack Overflow

I am reading an open source project and came to this part of code can someone explain what is going on here

import kotlin.properties.ReadWriteProperty

import kotlin.reflect.KProperty

inline fun observer(

initialValue: T,

crossinline onChange: (newValue: T) -> Unit

):

ReadWriteProperty =

object : ObservableProperty(initialValue) {

override fun afterChange(property: KProperty, oldValue: T, newValue: T) =

onChange(newValue)

}

this observer()

function was called in adapter class like this

var albums: List by observer(listOf()) {

notifyDataSetChanged()

}

whole adapter file

import android.view.LayoutInflater

import android.view.View

import android.view.ViewGroup

import androidx.recyclerview.widget.RecyclerView

import coil.api.load

import coil.transform.RoundedCornersTransformation

import com.igorwojda.showcase.feature.album.R

import com.igorwojda.showcase.feature.album.domain.model.AlbumDomainModel

import com.igorwojda.showcase.library.base.delegate.observer

import com.igorwojda.showcase.library.base.presentation.extension.setOnDebouncedClickListener

import com.pawegio.kandroid.hide

import com.pawegio.kandroid.show

import kotlinx.android.synthetic.main.fragment_album_list_item.view.*

internal class AlbumAdapter : RecyclerView.Adapter() {

var albums: List by observer(listOf()) {

notifyDataSetChanged()

}

private var onDebouncedClickListener: ((album: AlbumDomainModel) -> Unit)? = null

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {

val view = LayoutInflater.from(parent.context).inflate(R.layout.fragment_album_list_item, parent, false)

return MyViewHolder(view)

}

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {

holder.bind(albums[position])

}

override fun getItemCount(): Int = albums.size

fun setOnDebouncedClickListener(listener: (album: AlbumDomainModel) -> Unit) {

this.onDebouncedClickListener = listener

}

internal inner class MyViewHolder(

itemView: View

) : RecyclerView.ViewHolder(itemView) {

private var url by observer(null) {

itemView.coverErrorImageView.hide()

if (it == null) {

setDefaultImage()

} else {

itemView.coverImageView.load(it) {

crossfade(true)

error(R.drawable.ic_image)

transformations(RoundedCornersTransformation(10F))

}

}

}

fun bind(albumDomainModel: AlbumDomainModel) {

itemView.setOnDebouncedClickListener { onDebouncedClickListener?.invoke(albumDomainModel) }

url = albumDomainModel.getDefaultImageUrl()

}

private fun setDefaultImage() {

itemView.coverErrorImageView.show()

}

}

}

你可能感兴趣的:(android,mvi开发模式)