翻译:English
在 Compose 中你必须通过 AsyncImageState 的 loadState 和 progress 属性来监听请求的状态和进度,具体原因请参考 《Compose》,如下:
val state = rememberAsyncImageState()
val loadState: LoadState? = state.loadState
when (loadState) {
is Started -> {
}
is Success -> {
}
is Error -> {
}
is Canceled -> {
}
else -> {
// null
}
}
val progress: Progress? = state.progress
AsyncImage(
uri = imageUri,
contentDescription = "photo",
state = state
)
ImageRequest 通过 Listener 和 ProgressListener 可以监听开始、完成、错误、取消、进度,如下:
ImageRequest(context, "https://example.com/image.jpg") {
addListener(object : Listener {
override fun onStart(request: ImageRequest) {
// ...
}
override fun onSuccess(request: ImageRequest, result: ImageResult.Success) {
// ...
}
override fun onError(request: ImageRequest, error: ImageResult.Error) {
// ...
}
override fun onCancel(request: ImageRequest) {
// ...
}
})
// 或
addListener(
onStart = { request: ImageRequest ->
// ...
},
onSuccess = { request: ImageRequest, result: ImageResult.Success ->
// ...
},
onError = { request: ImageRequest, error: ImageResult.Error ->
// ...
},
onCancel = { request: ImageRequest ->
// ...
},
)
addProgressListener { request: ImageRequest, progress: Progress ->
// ...
}
}
Tip
所有回调都将在主线程执行
SketchImageView 提供了 Flow 的方式来监听请求的状态和进度,如下:
val sketchImageView = SketchImageView(context)
scope.launch {
sketchImageView.requestState.loadState.collect { loadState ->
when (loadState) {
is Started -> {
}
is Success -> {
}
is Error -> {
}
is Canceled -> {
}
else -> {
// null
}
}
}
}
scope.launch {
sketchImageView.requestState.progressState.collect { progress ->
}
}