``` @Singleton class TypefaceProvider @Inject cons...
# android
a
Copy code
@Singleton
class TypefaceProvider @Inject constructor(
        private val typeFaceLoader: TypeFaceLoader,
        private val typeFaceCache: TypeFaceCache
) {
    
    fun getTypeface(fontPath: String): Typeface? {

        var typeface = typeFaceCache.getTypeface(fontPath)

        if (typeface == null) {
            typeface = typeFaceLoader.loadTypeface(fontPath)
            if (typeface != null) typeFaceCache.addTypeface(fontPath, typeface)
        }

        return typeface

    }

}

@Singleton
class TypeFaceCache @Inject constructor() {
    private val fontsMap = HashMap<String, Typeface>()

    fun getTypeface(path: String): Typeface? {
        return fontsMap.get(path)
    }

    fun addTypeface(path: String, typeFace: Typeface) {
        fontsMap.put(path, typeFace)
    }
}

@Singleton
class TypeFaceLoader @Inject constructor() {

    @Inject lateinit var assets: AssetManager

    fun loadTypeface(path: String): Typeface? {

        try {
            return Typeface.createFromAsset(assets, path)
        } catch(e: Exception) {
            e.printStackTrace()
            return null
        }

    }

}