diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..971fb00 --- /dev/null +++ b/.gitignore @@ -0,0 +1,65 @@ +# Mac +.DS_Store + +# Built application files +*.apk +*.aar +*.ap_ +*.aab + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ +# Uncomment the following line in case you need and you don't have the release build type files in your app +# release/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# IntelliJ +*.iml +.idea/* + +# Keystore files +# Uncomment the following lines if you do not want to check your keystore files in. +#*.jks +#*.keystore + +# External native build folder generated in Android Studio 2.2 and later +.externalNativeBuild +.cxx/ + +# Google Services (e.g. APIs or Firebase) +# google-services.json + +# Version control +vcs.xml + +# lint +lint/intermediates/ +lint/generated/ +lint/outputs/ +lint/tmp/ \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/.name b/.idea/.name new file mode 100644 index 0000000..d9b4d53 --- /dev/null +++ b/.idea/.name @@ -0,0 +1 @@ +prefetchviewpool \ No newline at end of file diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..650a600 --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,140 @@ + + + + \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..79ee123 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..fb7f4a8 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/dictionaries/sergejlapin.xml b/.idea/dictionaries/sergejlapin.xml new file mode 100644 index 0000000..df26660 --- /dev/null +++ b/.idea/dictionaries/sergejlapin.xml @@ -0,0 +1,7 @@ + + + + prefetchviewpool + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..04526bd --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,26 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..9b76615 --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..6199cc2 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,9 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..989e2c5 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md index 59c9107..5b500b8 100644 --- a/README.md +++ b/README.md @@ -1 +1,68 @@ -# prefetchviewpool \ No newline at end of file +# PrefetchViewPool + +[![](https://jitpack.io/v/vivid-money/prefetchviewpool.svg)](https://jitpack.io/#vivid-money/prefetchviewpool) +[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) + +## What is it? + +A RecyclerView's RecycledViewPool extension that enables you to request specific item view types to be created in advance, prior to them being actually required + +## Why? + +— Prefetch items while you're loading data for binding + +— Shared view pool of the items for use throughout the whole app that could be prefetched as soon as you can get the Activity context + +## Usage + +If you're using some of the implementation modules(Coroutines, RxJava *, Executor) then the usage will be as simple as following: + +In your activity's `onCreate()` or fragment's `onViewCreated()` add + + +``` Kotlin +recycler.setupWithPrefetchViewPool { setPrefetchBound(viewType = 1, count = 20) } + .bindToLifecycle(lifecycleOwner = this) +``` + +and you're done + +## Sample + +You could see an example of usage in [sample](https://github.com/vivid-money/prefetchviewpool/blob/main/sample/src/main/java/vivid/money/prefetchviewpool/sample/MainActivity.kt) + +## Download +Library is distributed through JitPack + +#### Add repository in the root build.gradle +``` Gradle +subprojects { + repositories { + maven { url("https://jitpack.io") } + } +} +``` + +#### Add required modules: + +- Core - for core functionality of PrefetchViewPool where you have to provide your own implementation of ViewHolderSupplier + +`implementation("com.github.vivid-money.prefetchviewpool:prefetchviewpool-core:{latest-version}")` + +- Coroutines - for **Kotlin coroutines** implementation of ViewHolderSupplier + +`implementation("com.github.vivid-money.prefetchviewpool:prefetchviewpool-coroutines:{latest-version}")` + +- RxJava 3 - for **RxJava 3** implementation of ViewHolderSupplier + +`implementation("com.github.vivid-money.prefetchviewpool:prefetchviewpool-rxjava-3:{latest-version}")` + +- RxJava 2 - for **RxJava 2** implementation of ViewHolderSupplier + +`implementation("com.github.vivid-money.prefetchviewpool:prefetchviewpool-rxjava-2:{latest-version}")` + +- Executor - for **ExecutorService** implementation of ViewHolderSupplier + +`implementation("com.github.vivid-money.prefetchviewpool:prefetchviewpool-executor:{latest-version}")` + +**Note:** all modules except for `core` provide a useful extension to easy setup PrefetchViewPool with RecyclerView \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..4ec5e8d --- /dev/null +++ b/build.gradle @@ -0,0 +1,27 @@ +buildscript { + + apply from: "buildscript/dependencies.gradle" + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } + + dependencies { + classpath(deps.gradle.android) + classpath(deps.gradle.kotlin) + } +} + +subprojects { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} \ No newline at end of file diff --git a/buildscript/android-library.gradle b/buildscript/android-library.gradle new file mode 100644 index 0000000..1e28763 --- /dev/null +++ b/buildscript/android-library.gradle @@ -0,0 +1,15 @@ +android { + compileSdkVersion 30 + + defaultConfig.minSdkVersion 16 + defaultConfig.targetSdkVersion 30 + + compileOptions.sourceCompatibility = JavaVersion.VERSION_1_8 + compileOptions.targetCompatibility = JavaVersion.VERSION_1_8 + + kotlinOptions.jvmTarget = JavaVersion.VERSION_1_8.toString() + + variantFilter { + if (name == "debug") ignore = true + } +} \ No newline at end of file diff --git a/buildscript/dependencies.gradle b/buildscript/dependencies.gradle new file mode 100644 index 0000000..e07dd5e --- /dev/null +++ b/buildscript/dependencies.gradle @@ -0,0 +1,20 @@ +ext.deps = [ + gradle : [ + android: "com.android.tools.build:gradle:4.1.2", + kotlin : "org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.31" + ], + kotlin : [ + coroutines: "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3" + ], + androidx: [ + coreKtx : "androidx.core:core-ktx:1.3.2", + appCompat : "androidx.appcompat:appcompat:1.2.0", + constraintLayout: "androidx.constraintlayout:constraintlayout:2.0.4", + recyclerView : "androidx.recyclerview:recyclerview:1.1.0" + ], + google : [ + material: "com.google.android.material:material:1.3.0" + ], + rxJava2 : "io.reactivex.rxjava2:rxjava:2.2.19", + rxJava3 : "io.reactivex.rxjava3:rxjava:3.0.11" +] \ No newline at end of file diff --git a/buildscript/publishing.gradle b/buildscript/publishing.gradle new file mode 100644 index 0000000..3b4ffdb --- /dev/null +++ b/buildscript/publishing.gradle @@ -0,0 +1,34 @@ +apply plugin: "maven-publish" + +group = properties["lib.group"] +version = properties["lib.version"] + +task sourcesJar(type: Jar) { + archiveClassifier.set("sources") + from android.sourceSets.main.java.srcDirs +} + +task javadocs(type: Javadoc) { + failOnError false + source = android.sourceSets.main.java.sourceFiles + classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) + classpath += configurations.compile +} + +task javadocsJar(type: Jar, dependsOn: javadocs) { + archiveClassifier.set('javadoc') + from javadocs.destinationDir +} + +afterEvaluate { + publishing { + publications { + release(MavenPublication) { + from components.release + artifactId = project.name + artifact javadocsJar + artifact sourcesJar + } + } + } +} \ No newline at end of file diff --git a/buildscript/repositories.gradle b/buildscript/repositories.gradle new file mode 100644 index 0000000..bed36ac --- /dev/null +++ b/buildscript/repositories.gradle @@ -0,0 +1,4 @@ +repositories { + google() + mavenCentral() +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..3b044d2 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,18 @@ +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +org.gradle.parallel=true +org.gradle.configureondemand=true +org.gradle.daemon=true +org.gradle.caching=true +org.gradle.vfs.watch=true + +android.useAndroidX=true +android.defaults.buildfeatures.buildconfig=false +android.defaults.buildfeatures.aidl=false +android.defaults.buildfeatures.renderscript=false +android.defaults.buildfeatures.resvalues=false +android.defaults.buildfeatures.shaders=false + +kotlin.code.style=official + +lib.group=vivid.money.prefetchviewpool +lib.version=1.0.0 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e708b1c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..8cf6eb5 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..4f906e0 --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/lib/core/build.gradle b/lib/core/build.gradle new file mode 100644 index 0000000..35253b9 --- /dev/null +++ b/lib/core/build.gradle @@ -0,0 +1,11 @@ +plugins { + id("com.android.library") + id("kotlin-android") +} + +dependencies { + implementation(deps.androidx.recyclerView) +} + +apply from: rootProject.file("buildscript/android-library.gradle") +apply from: rootProject.file("buildscript/publishing.gradle") \ No newline at end of file diff --git a/lib/core/src/main/AndroidManifest.xml b/lib/core/src/main/AndroidManifest.xml new file mode 100644 index 0000000..65131e3 --- /dev/null +++ b/lib/core/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/lib/core/src/main/java/vivid/money/prefetchviewpool/core/PrefetchViewPool.kt b/lib/core/src/main/java/vivid/money/prefetchviewpool/core/PrefetchViewPool.kt new file mode 100644 index 0000000..8c1b462 --- /dev/null +++ b/lib/core/src/main/java/vivid/money/prefetchviewpool/core/PrefetchViewPool.kt @@ -0,0 +1,72 @@ +package vivid.money.prefetchviewpool.core + +import androidx.recyclerview.widget.RecyclerView +import androidx.recyclerview.widget.attachToPreventFromClearing +import androidx.recyclerview.widget.factorInCreateTime +import kotlin.math.max + +/** + * An implementation of [RecyclerView.RecycledViewPool] that is able to trigger item creation + * before they are actually required by [RecyclerView] + * + * @param defaultMaxRecycledViews — minimum amount of view holders of any view type that will be kept in view pool + * @param viewHolderSupplier — instance of a [ViewHolderSupplier] that will handle the actual item creation + */ +class PrefetchViewPool( + private val defaultMaxRecycledViews: Int, + private val viewHolderSupplier: ViewHolderSupplier +) : RecyclerView.RecycledViewPool() { + + private val recycledViewsBounds = mutableMapOf() + + init { + attachToPreventFromClearing() + viewHolderSupplier.viewHolderConsumer = ::putViewFromSupplier + viewHolderSupplier.start() + } + + /** + * Trigger actual item creation + * + * @param viewType — view type of the required view holders + * @param count — required amount of the view holders; it is used as max amount of recycled views of [viewType] + * in case it exceeds [defaultMaxRecycledViews] + */ + fun setPrefetchBound(viewType: Int, count: Int) { + recycledViewsBounds[viewType] = max(defaultMaxRecycledViews, count) + viewHolderSupplier.setPrefetchBound(viewType, count) + } + + override fun putRecycledView(scrap: RecyclerView.ViewHolder) { + val viewType = scrap.itemViewType + val maxRecycledViews = recycledViewsBounds.getOrPut(viewType) { defaultMaxRecycledViews } + setMaxRecycledViews(viewType, maxRecycledViews) + super.putRecycledView(scrap) + } + + override fun getRecycledView(viewType: Int): RecyclerView.ViewHolder? { + val holder = super.getRecycledView(viewType) + if (holder == null) viewHolderSupplier.onItemCreatedOutside(viewType) + return holder + } + + override fun clear() { + super.clear() + viewHolderSupplier.stop() + } + + /** + * Notifying [RecyclerView.RecycledViewPool] about item creation time is required for + * [androidx.recyclerview.widget.GapWorker] work, so this method does that before putting + * item, created in [viewHolderSupplier], into the pool + */ + private fun putViewFromSupplier(scrap: RecyclerView.ViewHolder, creationTimeNanos: Long) { + factorInCreateTime(scrap.itemViewType, creationTimeNanos) + putRecycledView(scrap) + } + + companion object { + + const val DEFAULT_MAX_RECYCLED_VIEWS = 5 + } +} \ No newline at end of file diff --git a/lib/core/src/main/java/vivid/money/prefetchviewpool/core/RecycledViewPoolBinder.kt b/lib/core/src/main/java/vivid/money/prefetchviewpool/core/RecycledViewPoolBinder.kt new file mode 100644 index 0000000..1a843e2 --- /dev/null +++ b/lib/core/src/main/java/vivid/money/prefetchviewpool/core/RecycledViewPoolBinder.kt @@ -0,0 +1,18 @@ +package vivid.money.prefetchviewpool.core + +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleObserver +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.OnLifecycleEvent +import androidx.recyclerview.widget.RecyclerView + +fun RecyclerView.RecycledViewPool.bindToLifecycle(lifecycleOwner: LifecycleOwner) { + val observer = object : LifecycleObserver { + + @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) + fun onDestroy() { + this@bindToLifecycle.clear() + } + } + lifecycleOwner.lifecycle.addObserver(observer) +} \ No newline at end of file diff --git a/lib/core/src/main/java/vivid/money/prefetchviewpool/core/RecyclerViewExt.kt b/lib/core/src/main/java/vivid/money/prefetchviewpool/core/RecyclerViewExt.kt new file mode 100644 index 0000000..4edeeba --- /dev/null +++ b/lib/core/src/main/java/vivid/money/prefetchviewpool/core/RecyclerViewExt.kt @@ -0,0 +1,9 @@ +package vivid.money.prefetchviewpool.core + +import androidx.recyclerview.widget.RecyclerView + +inline val RecyclerView.defaultViewHolderProducer: ViewHolderProducer + get() { + val adapter = requireNotNull(adapter) { "You have to set RecyclerView's adapter first" } + return adapter::createViewHolder + } \ No newline at end of file diff --git a/lib/core/src/main/java/vivid/money/prefetchviewpool/core/RecyclerViewProxy.kt b/lib/core/src/main/java/vivid/money/prefetchviewpool/core/RecyclerViewProxy.kt new file mode 100644 index 0000000..b9e7023 --- /dev/null +++ b/lib/core/src/main/java/vivid/money/prefetchviewpool/core/RecyclerViewProxy.kt @@ -0,0 +1,17 @@ +@file:Suppress("PackageDirectoryMismatch") + +package androidx.recyclerview.widget + +import vivid.money.prefetchviewpool.core.PrefetchViewPool + +internal fun RecyclerView.RecycledViewPool.attachToPreventFromClearing() { + attach() +} + +internal fun RecyclerView.ViewHolder.setItemViewType(viewType: Int) { + mItemViewType = viewType +} + +internal fun PrefetchViewPool.factorInCreateTime(viewType: Int, creationTimeNanos: Long) { + (this as RecyclerView.RecycledViewPool).factorInCreateTime(viewType, creationTimeNanos) +} \ No newline at end of file diff --git a/lib/core/src/main/java/vivid/money/prefetchviewpool/core/ViewHolderSupplier.kt b/lib/core/src/main/java/vivid/money/prefetchviewpool/core/ViewHolderSupplier.kt new file mode 100644 index 0000000..504bf88 --- /dev/null +++ b/lib/core/src/main/java/vivid/money/prefetchviewpool/core/ViewHolderSupplier.kt @@ -0,0 +1,122 @@ +package vivid.money.prefetchviewpool.core + +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.view.ViewGroup +import android.widget.FrameLayout +import androidx.recyclerview.widget.RecyclerView +import androidx.recyclerview.widget.setItemViewType +import java.util.concurrent.ConcurrentHashMap + +typealias ViewHolderProducer = (parent: ViewGroup, viewType: Int) -> RecyclerView.ViewHolder +typealias ViewHolderConsumer = (viewHolder: RecyclerView.ViewHolder, creationTimeNanos: Long) -> Unit + +/** + * This is responsible for scheduling item creation and notifying [viewHolderConsumer] whenever an item was created + * + * @param context — used only for creation of [fakeParent] + * @param viewHolderProducer — is used to actually create item + * (e.g. [androidx.recyclerview.widget.RecyclerView.Adapter]'s onCreateViewHolder() method) + */ +abstract class ViewHolderSupplier( + context: Context, + private val viewHolderProducer: ViewHolderProducer +) { + + /** + * Invoked once item is created in [createItem] + */ + internal lateinit var viewHolderConsumer: ViewHolderConsumer + + /** + * Passed as the parent to [viewHolderProducer] + */ + private val fakeParent: ViewGroup by lazy { FrameLayout(context) } + + /** + * Used for notifying [androidx.recyclerview.widget.RecyclerView.RecycledViewPool] of item have been created + */ + private val mainHandler: Handler = Handler(Looper.getMainLooper()) + + /** + * Used for calculation of item creation time + */ + private val nanoTime: Long get() = System.nanoTime() + + /** + * Holds info on how many items of certain view type are already created + */ + private val itemsCreated: MutableMap = ConcurrentHashMap() + + /** + * Holds info on how many items of certain view type are queued for creation + */ + private val itemsQueued: MutableMap = ConcurrentHashMap() + + /** + * Perform preparation actions required for item creation + */ + abstract fun start() + + /** + * Delegate actual item creation + */ + abstract fun enqueueItemCreation(viewType: Int) + + /** + * Clear all the resources required for item creation + */ + abstract fun stop() + + /** + * Creates view holder with the requested [viewType], if corresponding [itemsQueued] amount is not yet + * fulfilled. + * + * Assumes being called off the main thread so does the notification of [viewHolderConsumer] via + * main thread [Handler] + */ + protected fun createItem(viewType: Int) { + val created = itemsCreated.getOrZero(viewType) + 1 + val queued = itemsQueued.getOrZero(viewType) + if (created > queued) return + + val holder: RecyclerView.ViewHolder + val start: Long + val end: Long + + try { + start = nanoTime + holder = viewHolderProducer.invoke(fakeParent, viewType) + end = nanoTime + } catch (e: Exception) { + return + } + holder.setItemViewType(viewType) + itemsCreated[viewType] = itemsCreated.getOrZero(viewType) + 1 + + mainHandler.postAtFrontOfQueue { viewHolderConsumer.invoke(holder, end - start) } + } + + /** + * Calls [enqueueItemCreation] required amount of times in order to fill the recycled view pool + */ + internal fun setPrefetchBound(viewType: Int, count: Int) { + if (itemsQueued.getOrZero(viewType) >= count) return + itemsQueued[viewType] = count + + val created = itemsCreated.getOrZero(viewType) + if (created >= count) return + + repeat(count - created) { enqueueItemCreation(viewType) } + } + + /** + * One less item is required to be created here + */ + internal fun onItemCreatedOutside(viewType: Int) { + itemsCreated[viewType] = itemsCreated.getOrZero(viewType) + 1 + } + + private fun Map.getOrZero(key: Int) = getOrElse(key) { 0 } +} \ No newline at end of file diff --git a/lib/coroutines/build.gradle b/lib/coroutines/build.gradle new file mode 100644 index 0000000..552d795 --- /dev/null +++ b/lib/coroutines/build.gradle @@ -0,0 +1,15 @@ +plugins { + id("com.android.library") + id("kotlin-android") +} + +dependencies { + implementation(project(":prefetchviewpool-core")) + + implementation(deps.kotlin.coroutines) + + implementation(deps.androidx.recyclerView) +} + +apply from: rootProject.file("buildscript/android-library.gradle") +apply from: rootProject.file("buildscript/publishing.gradle") \ No newline at end of file diff --git a/lib/coroutines/src/main/AndroidManifest.xml b/lib/coroutines/src/main/AndroidManifest.xml new file mode 100644 index 0000000..98d7288 --- /dev/null +++ b/lib/coroutines/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/lib/coroutines/src/main/java/vivid/money/prefetchviewpool/coroutines/CoroutinesViewHolderSupplier.kt b/lib/coroutines/src/main/java/vivid/money/prefetchviewpool/coroutines/CoroutinesViewHolderSupplier.kt new file mode 100644 index 0000000..041eb73 --- /dev/null +++ b/lib/coroutines/src/main/java/vivid/money/prefetchviewpool/coroutines/CoroutinesViewHolderSupplier.kt @@ -0,0 +1,37 @@ +package vivid.money.prefetchviewpool.coroutines + +import android.content.Context +import kotlinx.coroutines.* +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.flow.receiveAsFlow +import vivid.money.prefetchviewpool.core.ViewHolderProducer +import vivid.money.prefetchviewpool.core.ViewHolderSupplier +import kotlin.coroutines.CoroutineContext + +class CoroutinesViewHolderSupplier( + context: Context, + viewHolderProducer: ViewHolderProducer +) : ViewHolderSupplier(context, viewHolderProducer), + CoroutineScope { + + override val coroutineContext: CoroutineContext + get() = SupervisorJob() + Dispatchers.Default + + private val channelFlow = Channel() + + override fun start() { + launch { + channelFlow.receiveAsFlow() + .collect { viewType -> launch { createItem(viewType) } } + } + } + + override fun enqueueItemCreation(viewType: Int) { + launch { channelFlow.send(viewType) } + } + + override fun stop() { + cancel() + } +} \ No newline at end of file diff --git a/lib/coroutines/src/main/java/vivid/money/prefetchviewpool/coroutines/RecyclerViewExt.kt b/lib/coroutines/src/main/java/vivid/money/prefetchviewpool/coroutines/RecyclerViewExt.kt new file mode 100644 index 0000000..2e893ff --- /dev/null +++ b/lib/coroutines/src/main/java/vivid/money/prefetchviewpool/coroutines/RecyclerViewExt.kt @@ -0,0 +1,17 @@ +package vivid.money.prefetchviewpool.coroutines + +import androidx.recyclerview.widget.RecyclerView +import vivid.money.prefetchviewpool.core.PrefetchViewPool +import vivid.money.prefetchviewpool.core.ViewHolderProducer +import vivid.money.prefetchviewpool.core.defaultViewHolderProducer + +fun RecyclerView.setupWithPrefetchViewPool( + defaultMaxRecycledViews: Int = PrefetchViewPool.DEFAULT_MAX_RECYCLED_VIEWS, + viewHolderProducer: ViewHolderProducer = defaultViewHolderProducer, + builder: PrefetchViewPool.() -> Unit = {} +): PrefetchViewPool { + val viewHolderSupplier = CoroutinesViewHolderSupplier(context, viewHolderProducer) + val prefetchViewPool = PrefetchViewPool(defaultMaxRecycledViews, viewHolderSupplier).apply(builder) + setRecycledViewPool(prefetchViewPool) + return prefetchViewPool +} \ No newline at end of file diff --git a/lib/executor/build.gradle b/lib/executor/build.gradle new file mode 100644 index 0000000..56ed764 --- /dev/null +++ b/lib/executor/build.gradle @@ -0,0 +1,13 @@ +plugins { + id("com.android.library") + id("kotlin-android") +} + +dependencies { + implementation(project(":prefetchviewpool-core")) + + implementation(deps.androidx.recyclerView) +} + +apply from: rootProject.file("buildscript/android-library.gradle") +apply from: rootProject.file("buildscript/publishing.gradle") \ No newline at end of file diff --git a/lib/executor/src/main/AndroidManifest.xml b/lib/executor/src/main/AndroidManifest.xml new file mode 100644 index 0000000..c5dc57c --- /dev/null +++ b/lib/executor/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/lib/executor/src/main/java/vivid/money/prefetchviewpool/executor/ExecutorViewHolderSupplier.kt b/lib/executor/src/main/java/vivid/money/prefetchviewpool/executor/ExecutorViewHolderSupplier.kt new file mode 100644 index 0000000..936008f --- /dev/null +++ b/lib/executor/src/main/java/vivid/money/prefetchviewpool/executor/ExecutorViewHolderSupplier.kt @@ -0,0 +1,26 @@ +package vivid.money.prefetchviewpool.executor + +import android.content.Context +import vivid.money.prefetchviewpool.core.ViewHolderProducer +import vivid.money.prefetchviewpool.core.ViewHolderSupplier +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors + +class ExecutorViewHolderSupplier( + context: Context, + viewHolderProducer: ViewHolderProducer +) : ViewHolderSupplier(context, viewHolderProducer) { + + private val executorService: ExecutorService = + Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()) + + override fun start() = Unit + + override fun enqueueItemCreation(viewType: Int) { + executorService.submit { createItem(viewType) } + } + + override fun stop() { + executorService.shutdown() + } +} \ No newline at end of file diff --git a/lib/executor/src/main/java/vivid/money/prefetchviewpool/executor/RecyclerViewExt.kt b/lib/executor/src/main/java/vivid/money/prefetchviewpool/executor/RecyclerViewExt.kt new file mode 100644 index 0000000..80f2167 --- /dev/null +++ b/lib/executor/src/main/java/vivid/money/prefetchviewpool/executor/RecyclerViewExt.kt @@ -0,0 +1,17 @@ +package vivid.money.prefetchviewpool.executor + +import androidx.recyclerview.widget.RecyclerView +import vivid.money.prefetchviewpool.core.PrefetchViewPool +import vivid.money.prefetchviewpool.core.ViewHolderProducer +import vivid.money.prefetchviewpool.core.defaultViewHolderProducer + +fun RecyclerView.setupWithPrefetchViewPool( + defaultMaxRecycledViews: Int = PrefetchViewPool.DEFAULT_MAX_RECYCLED_VIEWS, + viewHolderProducer: ViewHolderProducer = defaultViewHolderProducer, + builder: PrefetchViewPool.() -> Unit = {} +): PrefetchViewPool { + val viewHolderSupplier = ExecutorViewHolderSupplier(context, viewHolderProducer) + val prefetchViewPool = PrefetchViewPool(defaultMaxRecycledViews, viewHolderSupplier).apply(builder) + setRecycledViewPool(prefetchViewPool) + return prefetchViewPool +} \ No newline at end of file diff --git a/lib/rxjava-2/build.gradle b/lib/rxjava-2/build.gradle new file mode 100644 index 0000000..a1aa55b --- /dev/null +++ b/lib/rxjava-2/build.gradle @@ -0,0 +1,15 @@ +plugins { + id("com.android.library") + id("kotlin-android") +} + +dependencies { + implementation(project(":prefetchviewpool-core")) + + implementation(deps.rxJava2) + + implementation(deps.androidx.recyclerView) +} + +apply from: rootProject.file("buildscript/android-library.gradle") +apply from: rootProject.file("buildscript/publishing.gradle") \ No newline at end of file diff --git a/lib/rxjava-2/src/main/AndroidManifest.xml b/lib/rxjava-2/src/main/AndroidManifest.xml new file mode 100644 index 0000000..d084a71 --- /dev/null +++ b/lib/rxjava-2/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/lib/rxjava-2/src/main/java/vivid/money/prefetchviewpool/rxjava2/RecycleViewExt.kt b/lib/rxjava-2/src/main/java/vivid/money/prefetchviewpool/rxjava2/RecycleViewExt.kt new file mode 100644 index 0000000..d750b25 --- /dev/null +++ b/lib/rxjava-2/src/main/java/vivid/money/prefetchviewpool/rxjava2/RecycleViewExt.kt @@ -0,0 +1,17 @@ +package vivid.money.prefetchviewpool.rxjava2 + +import androidx.recyclerview.widget.RecyclerView +import vivid.money.prefetchviewpool.core.PrefetchViewPool +import vivid.money.prefetchviewpool.core.ViewHolderProducer +import vivid.money.prefetchviewpool.core.defaultViewHolderProducer + +fun RecyclerView.setupWithPrefetchViewPool( + defaultMaxRecycledViews: Int = PrefetchViewPool.DEFAULT_MAX_RECYCLED_VIEWS, + viewHolderProducer: ViewHolderProducer = defaultViewHolderProducer, + builder: PrefetchViewPool.() -> Unit = {} +): PrefetchViewPool { + val viewHolderSupplier = RxJava2ViewHolderSupplier(context, viewHolderProducer) + val prefetchViewPool = PrefetchViewPool(defaultMaxRecycledViews, viewHolderSupplier).apply(builder) + setRecycledViewPool(prefetchViewPool) + return prefetchViewPool +} \ No newline at end of file diff --git a/lib/rxjava-2/src/main/java/vivid/money/prefetchviewpool/rxjava2/RxJava2ViewHolderSupplier.kt b/lib/rxjava-2/src/main/java/vivid/money/prefetchviewpool/rxjava2/RxJava2ViewHolderSupplier.kt new file mode 100644 index 0000000..d9a5406 --- /dev/null +++ b/lib/rxjava-2/src/main/java/vivid/money/prefetchviewpool/rxjava2/RxJava2ViewHolderSupplier.kt @@ -0,0 +1,40 @@ +package vivid.money.prefetchviewpool.rxjava2 + +import android.content.Context +import io.reactivex.Completable +import io.reactivex.disposables.Disposable +import io.reactivex.schedulers.Schedulers.computation +import io.reactivex.subjects.PublishSubject +import vivid.money.prefetchviewpool.core.ViewHolderSupplier +import vivid.money.prefetchviewpool.core.ViewHolderProducer + +class RxJava2ViewHolderSupplier( + context: Context, + viewHolderProducer: ViewHolderProducer +) : ViewHolderSupplier(context, viewHolderProducer) { + + private val createSubject = PublishSubject.create() + + private var disposable: Disposable? = null + + override fun start() { + disposable = createSubject + .observeOn(computation()) + .flatMapCompletable { viewType -> createItemAsync(viewType) } + .subscribe() + } + + override fun enqueueItemCreation(viewType: Int) { + createSubject.onNext(viewType) + } + + override fun stop() { + disposable?.dispose() + } + + private fun createItemAsync(viewType: Int): Completable { + return Completable + .fromAction { createItem(viewType) } + .subscribeOn(computation()) + } +} \ No newline at end of file diff --git a/lib/rxjava-3/build.gradle b/lib/rxjava-3/build.gradle new file mode 100644 index 0000000..0228ae1 --- /dev/null +++ b/lib/rxjava-3/build.gradle @@ -0,0 +1,15 @@ +plugins { + id("com.android.library") + id("kotlin-android") +} + +dependencies { + implementation(project(":prefetchviewpool-core")) + + implementation(deps.rxJava3) + + implementation(deps.androidx.recyclerView) +} + +apply from: rootProject.file("buildscript/android-library.gradle") +apply from: rootProject.file("buildscript/publishing.gradle") \ No newline at end of file diff --git a/lib/rxjava-3/src/main/AndroidManifest.xml b/lib/rxjava-3/src/main/AndroidManifest.xml new file mode 100644 index 0000000..50b9113 --- /dev/null +++ b/lib/rxjava-3/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/lib/rxjava-3/src/main/java/vivid/money/prefetchviewpool/rxjava3/RecyclerViewExt.kt b/lib/rxjava-3/src/main/java/vivid/money/prefetchviewpool/rxjava3/RecyclerViewExt.kt new file mode 100644 index 0000000..4c2cc23 --- /dev/null +++ b/lib/rxjava-3/src/main/java/vivid/money/prefetchviewpool/rxjava3/RecyclerViewExt.kt @@ -0,0 +1,17 @@ +package vivid.money.prefetchviewpool.rxjava3 + +import androidx.recyclerview.widget.RecyclerView +import vivid.money.prefetchviewpool.core.PrefetchViewPool +import vivid.money.prefetchviewpool.core.ViewHolderProducer +import vivid.money.prefetchviewpool.core.defaultViewHolderProducer + +fun RecyclerView.setupWithPrefetchViewPool( + defaultMaxRecycledViews: Int = PrefetchViewPool.DEFAULT_MAX_RECYCLED_VIEWS, + viewHolderProducer: ViewHolderProducer = defaultViewHolderProducer, + builder: PrefetchViewPool.() -> Unit = {} +): PrefetchViewPool { + val viewHolderSupplier = RxJava3ViewHolderSupplier(context, viewHolderProducer) + val prefetchViewPool = PrefetchViewPool(defaultMaxRecycledViews, viewHolderSupplier).apply(builder) + setRecycledViewPool(prefetchViewPool) + return prefetchViewPool +} \ No newline at end of file diff --git a/lib/rxjava-3/src/main/java/vivid/money/prefetchviewpool/rxjava3/RxJava3ViewHolderSupplier.kt b/lib/rxjava-3/src/main/java/vivid/money/prefetchviewpool/rxjava3/RxJava3ViewHolderSupplier.kt new file mode 100644 index 0000000..b4a390e --- /dev/null +++ b/lib/rxjava-3/src/main/java/vivid/money/prefetchviewpool/rxjava3/RxJava3ViewHolderSupplier.kt @@ -0,0 +1,40 @@ +package vivid.money.prefetchviewpool.rxjava3 + +import android.content.Context +import io.reactivex.rxjava3.core.Completable +import io.reactivex.rxjava3.disposables.Disposable +import io.reactivex.rxjava3.schedulers.Schedulers.computation +import io.reactivex.rxjava3.subjects.PublishSubject +import vivid.money.prefetchviewpool.core.ViewHolderSupplier +import vivid.money.prefetchviewpool.core.ViewHolderProducer + +class RxJava3ViewHolderSupplier( + context: Context, + viewHolderProducer: ViewHolderProducer +) : ViewHolderSupplier(context, viewHolderProducer) { + + private val createSubject = PublishSubject.create() + + private var disposable: Disposable? = null + + override fun start() { + disposable = createSubject + .observeOn(computation()) + .flatMapCompletable { viewType -> createItemAsync(viewType) } + .subscribe() + } + + override fun enqueueItemCreation(viewType: Int) { + createSubject.onNext(viewType) + } + + override fun stop() { + disposable?.dispose() + } + + private fun createItemAsync(viewType: Int): Completable { + return Completable + .fromAction { createItem(viewType) } + .subscribeOn(computation()) + } +} \ No newline at end of file diff --git a/sample/build.gradle b/sample/build.gradle new file mode 100644 index 0000000..41f1e8a --- /dev/null +++ b/sample/build.gradle @@ -0,0 +1,50 @@ +plugins { + id("com.android.application") + id("kotlin-android") +} + +android { + compileSdkVersion 30 + buildToolsVersion "30.0.3" + + defaultConfig { + applicationId "vivid.money.prefetchviewpool.sample" + minSdkVersion 21 + targetSdkVersion 30 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + debug { + matchingFallbacks = ["release"] + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + kotlinOptions { + jvmTarget = "1.8" + } + + variantFilter { + if (name == "release") ignore = true + } +} + +dependencies { + implementation(project(":prefetchviewpool-core")) + implementation(project(":prefetchviewpool-coroutines")) + + implementation(deps.androidx.coreKtx) + implementation(deps.androidx.appCompat) + implementation(deps.androidx.constraintLayout) + implementation(deps.androidx.recyclerView) + + implementation(deps.google.material) +} \ No newline at end of file diff --git a/sample/proguard-rules.pro b/sample/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/sample/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/sample/src/main/AndroidManifest.xml b/sample/src/main/AndroidManifest.xml new file mode 100644 index 0000000..b10a76c --- /dev/null +++ b/sample/src/main/AndroidManifest.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sample/src/main/java/vivid/money/prefetchviewpool/sample/MainActivity.kt b/sample/src/main/java/vivid/money/prefetchviewpool/sample/MainActivity.kt new file mode 100644 index 0000000..f4d556f --- /dev/null +++ b/sample/src/main/java/vivid/money/prefetchviewpool/sample/MainActivity.kt @@ -0,0 +1,85 @@ +package vivid.money.prefetchviewpool.sample + +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import android.widget.TextView +import androidx.appcompat.app.AppCompatActivity +import androidx.core.os.postDelayed +import androidx.recyclerview.widget.DiffUtil +import androidx.recyclerview.widget.ListAdapter +import androidx.recyclerview.widget.RecyclerView +import vivid.money.prefetchviewpool.core.bindToLifecycle +import vivid.money.prefetchviewpool.coroutines.setupWithPrefetchViewPool + +class MainActivity : AppCompatActivity() { + + private val handler = Handler(Looper.getMainLooper()) + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + + val fl1 = FrameLayout(applicationContext) + val fl2 = FrameLayout(this) + + val recycler = findViewById(R.id.recycler) + val adapter = Adapter() + recycler.adapter = adapter + adapter.submitList(listOf(Unit)) + + handler.postDelayed(500) { + adapter.submitList(List(200) { "Fake item #$it" }) + } + + recycler + .setupWithPrefetchViewPool { setPrefetchBound(viewType = 1, count = 20) } + .bindToLifecycle(lifecycleOwner = this) + } +} + +class Adapter : ListAdapter(InvalidateUtilCallback()) { + + override fun getItemViewType(position: Int): Int = when (currentList[position]) { + is Unit -> 0 + else -> 1 + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = when (viewType) { + 0 -> { + val progressView = parent.inflate(R.layout.item_pb) + object : RecyclerView.ViewHolder(progressView) {} + } + 1 -> { + Thread.sleep(20) + val textView = parent.inflate(R.layout.item_tv) + object : RecyclerView.ViewHolder(textView) {} + } + else -> error("error") + } + + private fun ViewGroup.inflate(layoutResId: Int): View { + return LayoutInflater.from(context).inflate(layoutResId, this, false) + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + if (holder.itemViewType == 1) { + (holder.itemView as TextView).text = currentList[position] as String + } + } +} + +class InvalidateUtilCallback : DiffUtil.ItemCallback() { + + override fun areItemsTheSame(oldItem: Any, newItem: Any): Boolean { + return false + } + + override fun areContentsTheSame(oldItem: Any, newItem: Any): Boolean { + return false + } +} \ No newline at end of file diff --git a/sample/src/main/res/drawable-v24/ic_launcher_foreground.xml b/sample/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..2b068d1 --- /dev/null +++ b/sample/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/sample/src/main/res/drawable/ic_launcher_background.xml b/sample/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..07d5da9 --- /dev/null +++ b/sample/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sample/src/main/res/layout/activity_main.xml b/sample/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..de83d39 --- /dev/null +++ b/sample/src/main/res/layout/activity_main.xml @@ -0,0 +1,8 @@ + + \ No newline at end of file diff --git a/sample/src/main/res/layout/item_pb.xml b/sample/src/main/res/layout/item_pb.xml new file mode 100644 index 0000000..03f2367 --- /dev/null +++ b/sample/src/main/res/layout/item_pb.xml @@ -0,0 +1,10 @@ + + + + + \ No newline at end of file diff --git a/sample/src/main/res/layout/item_tv.xml b/sample/src/main/res/layout/item_tv.xml new file mode 100644 index 0000000..bc28998 --- /dev/null +++ b/sample/src/main/res/layout/item_tv.xml @@ -0,0 +1,5 @@ + + \ No newline at end of file diff --git a/sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..eca70cf --- /dev/null +++ b/sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..eca70cf --- /dev/null +++ b/sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/sample/src/main/res/mipmap-hdpi/ic_launcher.png b/sample/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..a571e60 Binary files /dev/null and b/sample/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png b/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 0000000..61da551 Binary files /dev/null and b/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/sample/src/main/res/mipmap-mdpi/ic_launcher.png b/sample/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..c41dd28 Binary files /dev/null and b/sample/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png b/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 0000000..db5080a Binary files /dev/null and b/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/sample/src/main/res/mipmap-xhdpi/ic_launcher.png b/sample/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..6dba46d Binary files /dev/null and b/sample/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 0000000..da31a87 Binary files /dev/null and b/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png b/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..15ac681 Binary files /dev/null and b/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..b216f2d Binary files /dev/null and b/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..f25a419 Binary files /dev/null and b/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..e96783c Binary files /dev/null and b/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/sample/src/main/res/values-night/themes.xml b/sample/src/main/res/values-night/themes.xml new file mode 100644 index 0000000..08d96a5 --- /dev/null +++ b/sample/src/main/res/values-night/themes.xml @@ -0,0 +1,16 @@ + + + + \ No newline at end of file diff --git a/sample/src/main/res/values/colors.xml b/sample/src/main/res/values/colors.xml new file mode 100644 index 0000000..f8c6127 --- /dev/null +++ b/sample/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/sample/src/main/res/values/strings.xml b/sample/src/main/res/values/strings.xml new file mode 100644 index 0000000..cb706a8 --- /dev/null +++ b/sample/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + Sample + \ No newline at end of file diff --git a/sample/src/main/res/values/themes.xml b/sample/src/main/res/values/themes.xml new file mode 100644 index 0000000..4599222 --- /dev/null +++ b/sample/src/main/res/values/themes.xml @@ -0,0 +1,16 @@ + + + + \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..1d3a28e --- /dev/null +++ b/settings.gradle @@ -0,0 +1,15 @@ +rootProject.name = "prefetchviewpool" + +include(":sample") + +void includeProject(final String name, final String path) { + include(name) + final def projectDir = new File(rootDir, path) + project(name).projectDir = projectDir +} + +includeProject(":prefetchviewpool-core", "lib/core") +includeProject(":prefetchviewpool-coroutines", "lib/coroutines") +includeProject(":prefetchviewpool-rxjava-2", "lib/rxjava-2") +includeProject(":prefetchviewpool-rxjava-3", "lib/rxjava-3") +includeProject(":prefetchviewpool-executor", "lib/executor")