Skip to content

Commit f5b4246

Browse files
committed
Initial commit
0 parents  commit f5b4246

38 files changed

+967
-0
lines changed

.gitignore

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
*.iml
2+
.gradle
3+
/local.properties
4+
/.idea/caches
5+
/.idea/libraries
6+
/.idea/modules.xml
7+
/.idea/workspace.xml
8+
/.idea/navEditor.xml
9+
/.idea/assetWizardSettings.xml
10+
.DS_Store
11+
/build
12+
/captures
13+
.externalNativeBuild
14+
.cxx

app/.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/build

app/build.gradle

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
apply plugin: 'com.android.application'
2+
apply plugin: 'kotlin-android'
3+
4+
android {
5+
compileSdkVersion 29
6+
buildToolsVersion "29.0.3"
7+
8+
defaultConfig {
9+
applicationId "com.hoc.mergeadapter_sample"
10+
minSdkVersion 23
11+
targetSdkVersion 29
12+
versionCode 1
13+
versionName "1.0"
14+
15+
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
16+
}
17+
18+
buildTypes {
19+
release {
20+
minifyEnabled false
21+
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
22+
}
23+
}
24+
25+
compileOptions {
26+
sourceCompatibility = 1.8
27+
targetCompatibility = 1.8
28+
}
29+
30+
kotlinOptions {
31+
jvmTarget = "1.8"
32+
}
33+
34+
viewBinding {
35+
enabled = true
36+
}
37+
38+
}
39+
40+
dependencies {
41+
implementation fileTree(dir: 'libs', include: ['*.jar'])
42+
43+
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
44+
implementation 'androidx.appcompat:appcompat:1.1.0'
45+
implementation 'androidx.core:core-ktx:1.2.0'
46+
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
47+
implementation "androidx.recyclerview:recyclerview:1.2.0-alpha02"
48+
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0'
49+
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
50+
implementation 'androidx.fragment:fragment-ktx:1.2.3'
51+
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
52+
53+
// coroutines
54+
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.5'
55+
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.5'
56+
57+
testImplementation 'junit:junit:4.12'
58+
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
59+
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
60+
}

app/proguard-rules.pro

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Add project specific ProGuard rules here.
2+
# You can control the set of applied configuration files using the
3+
# proguardFiles setting in build.gradle.
4+
#
5+
# For more details, see
6+
# http://developer.android.com/guide/developing/tools/proguard.html
7+
8+
# If your project uses WebView with JS, uncomment the following
9+
# and specify the fully qualified class name to the JavaScript interface
10+
# class:
11+
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12+
# public *;
13+
#}
14+
15+
# Uncomment this to preserve the line number information for
16+
# debugging stack traces.
17+
#-keepattributes SourceFile,LineNumberTable
18+
19+
# If you keep the line number information, uncomment this to
20+
# hide the original source file name.
21+
#-renamesourcefileattribute SourceFile
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.hoc.mergeadapter_sample
2+
3+
import androidx.test.platform.app.InstrumentationRegistry
4+
import androidx.test.ext.junit.runners.AndroidJUnit4
5+
6+
import org.junit.Test
7+
import org.junit.runner.RunWith
8+
9+
import org.junit.Assert.*
10+
11+
/**
12+
* Instrumented test, which will execute on an Android device.
13+
*
14+
* See [testing documentation](http://d.android.com/tools/testing).
15+
*/
16+
@RunWith(AndroidJUnit4::class)
17+
class ExampleInstrumentedTest {
18+
@Test
19+
fun useAppContext() {
20+
// Context of the app under test.
21+
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22+
assertEquals("com.hoc.mergeadapter_sample", appContext.packageName)
23+
}
24+
}

app/src/main/AndroidManifest.xml

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
3+
package="com.hoc.mergeadapter_sample">
4+
5+
<application
6+
android:allowBackup="true"
7+
android:icon="@mipmap/ic_launcher"
8+
android:label="@string/app_name"
9+
android:roundIcon="@mipmap/ic_launcher_round"
10+
android:supportsRtl="true"
11+
android:theme="@style/AppTheme">
12+
<activity android:name=".MainActivity">
13+
<intent-filter>
14+
<action android:name="android.intent.action.MAIN" />
15+
16+
<category android:name="android.intent.category.LAUNCHER" />
17+
</intent-filter>
18+
</activity>
19+
</application>
20+
21+
</manifest>
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.hoc.mergeadapter_sample
2+
3+
import kotlinx.coroutines.delay
4+
import java.util.concurrent.atomic.AtomicBoolean
5+
import java.util.concurrent.atomic.AtomicInteger
6+
7+
data class User(
8+
val uid: Int,
9+
val name: String,
10+
val email: String
11+
)
12+
13+
sealed class LoadingState {
14+
object Loading : LoadingState()
15+
data class Error(val throwable: Throwable) : LoadingState()
16+
}
17+
18+
object ApiError : Throwable(message = "Api error")
19+
20+
suspend fun getUsers(start: Int, limit: Int): List<User> {
21+
delay(2_000)
22+
23+
if (count.getAndIncrement() == 2 && throwError.compareAndSet(true, false)) {
24+
throw ApiError
25+
}
26+
27+
return List(limit) {
28+
User(
29+
uid = start + it,
30+
name = "Name ${start + it}",
31+
email = "email${start + it}@gmail.com",
32+
)
33+
}
34+
}
35+
36+
private val count = AtomicInteger(0)
37+
private val throwError = AtomicBoolean(true)
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package com.hoc.mergeadapter_sample
2+
3+
import android.view.LayoutInflater
4+
import android.view.View
5+
import android.view.ViewGroup
6+
import androidx.recyclerview.widget.DiffUtil
7+
import androidx.recyclerview.widget.ListAdapter
8+
import androidx.recyclerview.widget.RecyclerView
9+
import com.hoc.mergeadapter_sample.databinding.ItemFooterBinding
10+
11+
class FooterAdapter(private val onRetry: () -> Unit) :
12+
ListAdapter<LoadingState, FooterAdapter.VH>(object : DiffUtil.ItemCallback<LoadingState>() {
13+
override fun areItemsTheSame(oldItem: LoadingState, newItem: LoadingState) = true
14+
override fun areContentsTheSame(oldItem: LoadingState, newItem: LoadingState) =
15+
oldItem == newItem
16+
}) {
17+
18+
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = VH(
19+
ItemFooterBinding.inflate(
20+
LayoutInflater.from(parent.context),
21+
parent,
22+
false
23+
)
24+
)
25+
26+
override fun onBindViewHolder(holder: VH, position: Int) = holder.bind(getItem(position))
27+
28+
inner class VH(private val binding: ItemFooterBinding) : RecyclerView.ViewHolder(binding.root) {
29+
init {
30+
binding.buttonRetry.setOnClickListener {
31+
onRetry()
32+
}
33+
}
34+
35+
fun bind(item: LoadingState) {
36+
when (item) {
37+
LoadingState.Loading -> {
38+
binding.run {
39+
buttonRetry.visibility = View.INVISIBLE
40+
textViewError.visibility = View.INVISIBLE
41+
progressBar.visibility = View.VISIBLE
42+
}
43+
}
44+
is LoadingState.Error -> {
45+
binding.run {
46+
buttonRetry.visibility = View.VISIBLE
47+
textViewError.visibility = View.VISIBLE
48+
textViewError.text = item.throwable.message
49+
progressBar.visibility = View.INVISIBLE
50+
}
51+
}
52+
}
53+
}
54+
}
55+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package com.hoc.mergeadapter_sample
2+
3+
import android.os.Bundle
4+
import androidx.activity.viewModels
5+
import androidx.appcompat.app.AppCompatActivity
6+
import androidx.lifecycle.Observer
7+
import androidx.recyclerview.widget.LinearLayoutManager
8+
import androidx.recyclerview.widget.MergeAdapter
9+
import androidx.recyclerview.widget.RecyclerView
10+
import com.hoc.mergeadapter_sample.databinding.ActivityMainBinding
11+
import kotlin.LazyThreadSafetyMode.NONE
12+
13+
class MainActivity : AppCompatActivity() {
14+
private val vm by viewModels<MainVM>()
15+
16+
private val userAdapter = UserAdapter()
17+
private val footerAdapter = FooterAdapter(this::onRetry)
18+
19+
private val binding by lazy(NONE) {
20+
ActivityMainBinding.inflate(layoutInflater)
21+
}
22+
23+
override fun onCreate(savedInstanceState: Bundle?) {
24+
super.onCreate(savedInstanceState)
25+
setContentView(binding.root)
26+
27+
binding.recyclerView.run {
28+
setHasFixedSize(true)
29+
val linearLayoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
30+
layoutManager = linearLayoutManager
31+
adapter = MergeAdapter(userAdapter, footerAdapter)
32+
addOnScrollListener(object : RecyclerView.OnScrollListener() {
33+
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
34+
if (dy > 0
35+
&& linearLayoutManager.findLastVisibleItemPosition() + VISIBLE_THRESHOLD >= linearLayoutManager.itemCount
36+
) {
37+
vm.loadNextPage()
38+
}
39+
}
40+
})
41+
}
42+
43+
44+
vm.loadingStateLiveData.observe(this, Observer {
45+
footerAdapter.submitList(it)
46+
})
47+
vm.userLiveData.observe(this, Observer {
48+
userAdapter.submitList(it)
49+
})
50+
vm.loadNextPage()
51+
}
52+
53+
private fun onRetry() = vm.retryNextPage()
54+
55+
private companion object {
56+
private const val VISIBLE_THRESHOLD = 3
57+
}
58+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.hoc.mergeadapter_sample
2+
3+
import androidx.annotation.MainThread
4+
import androidx.lifecycle.*
5+
import kotlinx.coroutines.launch
6+
7+
8+
class MainVM : ViewModel() {
9+
private val usersD = MutableLiveData<List<User>>().apply { value = emptyList() }
10+
val userLiveData: LiveData<List<User>> get() = usersD
11+
12+
private val loadingStateD =
13+
MutableLiveData<PlaceholderState>().apply { value = PlaceholderState.Idle }
14+
val loadingStateLiveData: LiveData<List<LoadingState>>
15+
get() = loadingStateD.map {
16+
when (it) {
17+
null -> emptyList()
18+
PlaceholderState.Idle -> emptyList()
19+
PlaceholderState.Loading -> listOf(LoadingState.Loading)
20+
is PlaceholderState.Error -> listOf(LoadingState.Error(it.throwable))
21+
}
22+
}
23+
24+
@MainThread
25+
fun loadNextPage() {
26+
val state = loadingStateD.value
27+
if (state === null || state is PlaceholderState.Idle) {
28+
_loadNextPage()
29+
}
30+
}
31+
32+
@MainThread
33+
fun retryNextPage() {
34+
if (loadingStateD.value is PlaceholderState.Error) {
35+
_loadNextPage()
36+
}
37+
}
38+
39+
@Suppress("FunctionName")
40+
private fun _loadNextPage() {
41+
viewModelScope.launch {
42+
loadingStateD.value = PlaceholderState.Loading
43+
44+
val currentList = usersD.value ?: emptyList()
45+
kotlin.runCatching { getUsers(start = currentList.size, limit = LIMIT) }
46+
.fold(
47+
onSuccess = {
48+
usersD.value = currentList + it
49+
loadingStateD.value = PlaceholderState.Idle
50+
},
51+
onFailure = {
52+
loadingStateD.value = PlaceholderState.Error(it)
53+
}
54+
)
55+
}
56+
}
57+
58+
private sealed class PlaceholderState {
59+
object Idle : PlaceholderState()
60+
object Loading : PlaceholderState()
61+
data class Error(val throwable: Throwable) : PlaceholderState()
62+
}
63+
64+
private companion object {
65+
const val LIMIT = 20
66+
}
67+
}

0 commit comments

Comments
 (0)