Skip to content

Latest commit

 

History

History
125 lines (92 loc) · 5.71 KB

fetcher.md

File metadata and controls

125 lines (92 loc) · 5.71 KB

Fetcher

Translations: 简体中文

Fetcher is used to get data from uri, return FetchResult, and hand it over to Decoder for use.

Each uri supported by Sketch has a corresponding Fetcher implementation, as shown in the following table:

URI Fetcher Create Dependent modules Android iOS Desktop Web
http://, https:// HttpUriFetcher - -
file://, / FileUriFetcher newFileUri() -
compose.resource:// ComposeResourceUriFetcher newComposeResourceUri() sketch-compose-resources
data:image/, data:img/ Base64UriFetcher newBase64Uri() -
asset:// AssetUriFetcher newAssetUri() -
content:// ContentUriFetcher - -
android.resource:// ResourceUriFetcher newResourceUri() -
app.icon:// AppIconUriFetcher newAppIconUri() sketch-extensions-core
kotlin.resource:// KotlinResourceUriFetcher newKotlinResourceUri() -

Register Fetcher

Fetcher that needs to rely on a separate module (such as ComposeResourceUriFetcher) needs to be registered when initializing Sketch, as follows:

// Register for all ImageRequests when customizing Sketch
Sketch.Builder(context).apply {
    components {
        addFetcher(ComposeResourceUriFetcher.Factory())
    }
}.build()

// Register for a single ImageRequest when loading an image
ImageRequest(context, "https://www.example.com/image.gif") {
    components {
        addFetcher(ComposeResourceUriFetcher.Factory())
    }
}

Extend Fetcher

First implement the Fetcher interface to define your Fetcher and its Factory, and then register it through the addFetcher() method, as follows:

class MyFetcher : Fetcher {

    override suspend fun fetch(): Result<FetchResult> {
        // Parse your uri here and get the data
    }

    companion object {
        const val MY_SCHEME = "myUri"
    }

    class Factory : Fetcher.Factory {

        override fun create(sketch: Sketch, request: ImageRequest): MyFetcher? {
            return if (request.uri.startWith("$MY_SCHEME://")) {
                MyFetcher()
            } else {
                null
            }
        }
    }
}

// Register for all ImageRequests when customizing Sketch
Sketch.Builder(context).apply {
    components {
        addFetcher(MyFetcher.Factory())
    }
}.build()

// Register for a single ImageRequest when loading an image
ImageRequest(context, "myUri://sample.jpeg") {
    components {
        addFetcher(MyFetcher.Factory())
    }
}