From 5886c3d3dd3f83eb8ed081fc405256253dc4810d 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. --- .../main/java/com/squareup/cycler/Recycler.kt | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/lib/src/main/java/com/squareup/cycler/Recycler.kt b/lib/src/main/java/com/squareup/cycler/Recycler.kt index a2cd554..e9a3863 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 = { @@ -380,13 +380,27 @@ class Recycler internal constructor( } /** - * General method which is called from Extension code. DON'T USE DIRECTLY. + * General method which is called from extensions' code. + * Adds an [ExtensionSpec] to the [Config]. * @hide */ fun extension(spec: ExtensionSpec) { extensionSpecs.add(spec) } + /** + * General method which is called from extensions' code. + * 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 + .filterIsInstance() + .firstOrNull() + ?: block().also(extensionSpecs::add) + } + /** * Public method only for inlining, don't use directly. Use [Recycler.create] instead. * @hide