All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.seiko.imageloader.ImageLoaderBuilder.kt Maven / Gradle / Ivy

There is a newer version: 1.9.0
Show newest version
package com.seiko.imageloader

import com.seiko.imageloader.cache.disk.DiskCache
import com.seiko.imageloader.cache.memory.MemoryCache
import com.seiko.imageloader.cache.memory.MemoryCacheBuilder
import com.seiko.imageloader.component.ComponentRegistryBuilder
import com.seiko.imageloader.intercept.Interceptor
import com.seiko.imageloader.request.Options
import com.seiko.imageloader.util.ioDispatcher
import io.ktor.client.HttpClient
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob

expect class ImageLoaderBuilder : CommonImageLoaderBuilder {
    fun build(): ImageLoader
}

abstract class CommonImageLoaderBuilder> {

    protected val componentBuilder = ComponentRegistryBuilder()
    protected val interceptors = mutableListOf()
    protected var options: Options? = null

    protected abstract var httpClient: Lazy
    protected var memoryCache: Lazy = lazy { MemoryCacheBuilder().build() }
    protected var diskCache: Lazy? = null
    protected var requestDispatcher: CoroutineDispatcher = ioDispatcher
    protected var imageScope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)

    private inline fun apply(block: () -> Unit): B {
        block()
        @Suppress("UNCHECKED_CAST")
        return this as B
    }

    fun httpClient(initializer: () -> HttpClient) = apply {
        httpClient = lazy(initializer)
    }

    fun memoryCache(initializer: () -> MemoryCache) = apply {
        memoryCache = lazy(initializer)
    }

    fun diskCache(initializer: () -> DiskCache) = apply {
        diskCache = lazy(initializer)
    }

    fun components(builder: ComponentRegistryBuilder.() -> Unit) = apply {
        componentBuilder.run(builder)
    }

    fun addInterceptor(interceptor: Interceptor) = apply {
        interceptors.add(interceptor)
    }

    fun options(options: Options) = apply {
        this.options = options
    }

    fun requestDispatcher(dispatcher: CoroutineDispatcher) = apply {
        this.requestDispatcher = dispatcher
    }

    fun imageScope(scope: CoroutineScope) = apply {
        this.imageScope = scope
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy