数据监听类DataListenerController :
class DataListenerController<T> {
private val blocks = arrayListOf<(T?) -> Unit>()
var value: T? = null
set(value: T?) {
if (Looper.getMainLooper().thread == Thread.currentThread()) {
blocks.forEach { it.invoke(value) }
} else {
App.handler.post {
blocks.forEach { it.invoke(value) }
}
}
}
fun addListener(block: (T?) -> Unit) {
if (!blocks.contains(block)) {
blocks.add(block)
}
}
}
App 类:
class App : Application() {
companion object {
val handler = Handler()
}
override fun onCreate() {
super.onCreate()
Utils.init(this)
}
}
以下是MVP 模式下的Presenter :
class MusicsPresenter {
enum class MusicsLoadState {
LOADING, EMPTY, SUCCESS, ERROR
}
private val musicsMode by lazy {
MusicsModel()
}
val musicList = DataListenerController<List<Music>>()
val loadState = DataListenerController<MusicsLoadState>()
private val page = 1
private val size = 20
fun getMusic() {
loadState.value = MusicsLoadState.LOADING
musicsMode.loadMusicsByPage(page, size, object : MusicsModel.OnMusicLoadResult {
override fun onSuccess(result: List<Music>) {
musicList.value = result
loadState.value = if (result.isEmpty()) {
MusicsLoadState.EMPTY
} else {
MusicsLoadState.SUCCESS
}
}
override fun onError(msg: String, code: Int) {
loadState.value = MusicsLoadState.ERROR
println("error...$msg...$code")
}
})
}
}
View 层:
class MusicsActivity : AppCompatActivity() {
private val musicsPresenter by lazy {
MusicsPresenter()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_musics)
initDataListener()
initListener()
}
private fun initDataListener() {
musicsPresenter.musicList.addListener {
println(Thread.currentThread().name)
println("长度: ${it?.size}")
musicCountText?.text = "长度: ${it?.size}"
}
musicsPresenter.loadState.addListener {
println("状态: $it")
}
}
private fun initListener() {
getMusicsBtn.setOnClickListener {
musicsPresenter.getMusic()
}
}
}
Model 层:
class MusicsModel {
fun loadMusicsByPage(page: Int, size: Int, callback: OnMusicLoadResult) {
val result = arrayListOf<Music>()
Thread {
for (i in (0..size)) {
result.add(
Music("音乐的名称: $i", "封面: $i", "url: $i")
)
}
callback.onSuccess(result)
}.start()
}
interface OnMusicLoadResult {
fun onSuccess(result: List<Music>)
fun onError(msg: String, code: Int)
}
}
|