You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
107 lines
3.4 KiB
107 lines
3.4 KiB
package com.gyf.csams.uikit
|
|
|
|
import android.app.Application
|
|
import androidx.compose.ui.graphics.ImageBitmap
|
|
import androidx.lifecycle.AndroidViewModel
|
|
import androidx.lifecycle.LiveData
|
|
import androidx.lifecycle.MutableLiveData
|
|
import androidx.lifecycle.viewModelScope
|
|
import com.google.gson.reflect.TypeToken
|
|
import com.gyf.csams.R
|
|
import com.gyf.csams.util.SimpleCallback
|
|
import com.gyf.csams.util.Token
|
|
import com.gyf.csams.util.TokenManager
|
|
import com.gyf.lib.util.HttpClient
|
|
import com.gyf.lib.util.ImageUtil
|
|
import com.orhanobut.logger.Logger
|
|
import kotlinx.coroutines.Job
|
|
import kotlinx.coroutines.delay
|
|
import kotlinx.coroutines.launch
|
|
|
|
|
|
sealed class BaseVo {
|
|
abstract val token: Token
|
|
}
|
|
|
|
data class OnlyToken(
|
|
override val token: Token = TokenManager.token ?: throw IllegalArgumentException("无法获取token")
|
|
) : BaseVo()
|
|
|
|
class ImageModel(application: Application, private val urlPath: String) :
|
|
AndroidViewModel(application) {
|
|
private val _image = MutableLiveData<ImageBitmap>()
|
|
private val _imageUrls = MutableLiveData<List<String>?>()
|
|
val image: LiveData<ImageBitmap> = _image
|
|
private var job: Job? = null
|
|
private val _error = MutableLiveData<String?>()
|
|
val error: LiveData<String?> = _error
|
|
|
|
fun clearError() {
|
|
_error.value = null
|
|
}
|
|
|
|
/**
|
|
* 加载默认图片
|
|
*
|
|
*/
|
|
private fun defaultLoad() {
|
|
viewModelScope.launch {
|
|
_image.postValue(
|
|
ImageUtil.getImage(
|
|
getApplication(),
|
|
R.drawable.ic_launcher_foreground
|
|
)
|
|
)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 循环加载网络图片
|
|
*
|
|
*/
|
|
fun start() {
|
|
Logger.i("启动轮播")
|
|
if (job == null || job?.isCompleted == true || job?.isCancelled == true) {
|
|
job = viewModelScope.launch {
|
|
HttpClient.get(
|
|
url = urlPath,
|
|
SimpleCallback<List<String>>("获取轮播图", onSuccess = {
|
|
_imageUrls.postValue(it.body)
|
|
var index = 0
|
|
_imageUrls.value?.apply {
|
|
viewModelScope.launch {
|
|
do {
|
|
val imageBitmap =
|
|
ImageUtil.getImage(
|
|
context = getApplication(),
|
|
data = get(index)
|
|
)
|
|
Logger.e("成功从image url:${get(index)}解析图片")
|
|
imageBitmap?.apply {
|
|
_image.postValue(this)
|
|
}
|
|
delay(5000)
|
|
index = if (index == size - 1) 0 else index.plus(1)
|
|
} while (job?.isActive == true)
|
|
}
|
|
}
|
|
}, onFail = {
|
|
Logger.e("无法从接口地址:${urlPath}获取图片url列表")
|
|
_error.postValue(it)
|
|
defaultLoad()
|
|
}, type = object : TypeToken<List<String>>() {}.type)
|
|
)
|
|
}.apply {
|
|
start()
|
|
}
|
|
}
|
|
}
|
|
|
|
fun cancel() {
|
|
Logger.i("停止轮播")
|
|
job?.cancel()
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|