From 038016afa74126c6374045ebb55622a01c2e835c Mon Sep 17 00:00:00 2001 From: Helios Alonso Cabanillas Date: Tue, 20 Apr 2021 11:11:03 -0700 Subject: [PATCH] Add a Config.extension(block) Allows for extension code to optionally add an extension if not present. This might be needed in some cases where a feature (like a DSL that help define row types) need to access a common-shared object associated to the recycler. --- lib/src/main/java/com/squareup/cycler/Recycler.kt | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/src/main/java/com/squareup/cycler/Recycler.kt b/lib/src/main/java/com/squareup/cycler/Recycler.kt index a2cd554..95975bb 100644 --- a/lib/src/main/java/com/squareup/cycler/Recycler.kt +++ b/lib/src/main/java/com/squareup/cycler/Recycler.kt @@ -261,7 +261,7 @@ class Recycler internal constructor( @PublishedApi internal val rowSpecs = mutableListOf>() @PublishedApi internal val extraItemSpecs = mutableListOf>() - internal val extensionSpecs = mutableListOf>() + @PublishedApi internal val extensionSpecs = mutableListOf>() internal var hasStableIdProvider = false internal var stableIdProvider: StableIdProvider = { @@ -381,12 +381,25 @@ class Recycler internal constructor( /** * General method which is called from Extension code. DON'T USE DIRECTLY. + * Adds an [ExtensionSpec] to the [Config]. * @hide */ fun extension(spec: ExtensionSpec) { extensionSpecs.add(spec) } + /** + * General method which is called from Extension code. DON'T USE DIRECTLY. + * Returns the [ExtensionSpec] of type [E]. If not present [block] will be + * used to create it and add it. + * @hide + */ + inline fun > extension(block: () -> E): E { + return extensionSpecs + .firstOrNull { it is E } as E? + ?: block().also(extensionSpecs::add) + } + /** * Public method only for inlining, don't use directly. Use [Recycler.create] instead. * @hide