Skip to content

Latest commit

 

History

History
129 lines (99 loc) · 2.93 KB

listener_zh.md

File metadata and controls

129 lines (99 loc) · 2.93 KB

Listener

翻译:English

Compose

在 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
)

Android View

ImageRequest 通过 ListenerProgressListener 可以监听开始、完成、错误、取消、进度,如下:

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

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 ->

    }
}