11package com.hoc.pagination_mvi.ui.main
22
33import android.graphics.Rect
4+ import android.os.Parcelable
45import android.util.Log
56import android.view.LayoutInflater
67import android.view.View
@@ -51,6 +52,8 @@ private object DiffUtilItemCallback : DiffUtil.ItemCallback<Item>() {
5152
5253class MainAdapter (private val compositeDisposable : CompositeDisposable ) :
5354 ListAdapter <Item , MainAdapter .VH >(DiffUtilItemCallback ) {
55+ private val scrollToFirst = PublishSubject .create<Unit >()
56+ private var layoutManagerSavedState: Parcelable ? = null
5457
5558 private val retryS = PublishSubject .create<Unit >()
5659 val retryObservable get() = retryS.asObservable()
@@ -167,14 +170,18 @@ class MainAdapter(private val compositeDisposable: CompositeDisposable) :
167170 private val progressBar = itemView.progress_bar_horizontal!!
168171 private val textError = itemView.text_error_horizontal!!
169172 private val buttonRetry = itemView.button_retry_horizontal!!
173+
170174 private val adapter = HorizontalAdapter (compositeDisposable)
171175 private val visibleThreshold get() = 2
176+ internal val linearLayoutManager =
177+ LinearLayoutManager (itemView.context, RecyclerView .HORIZONTAL , false )
172178
173179 init {
174180 recycler.run {
175181 setHasFixedSize(true )
176182 adapter = this @HorizontalListVH.adapter
177- layoutManager = LinearLayoutManager (context, RecyclerView .HORIZONTAL , false )
183+ layoutManager = this @HorizontalListVH.linearLayoutManager
184+
178185 addItemDecoration(object : RecyclerView .ItemDecoration () {
179186 override fun getItemOffsets (
180187 outRect : Rect ,
@@ -216,6 +223,10 @@ class MainAdapter(private val compositeDisposable: CompositeDisposable) :
216223 }
217224 .subscribeBy { loadNextPageHorizontalS.onNext(Unit ) }
218225 .addTo(compositeDisposable)
226+
227+ scrollToFirst
228+ .subscribeBy { recycler.scrollToPosition(0 ) }
229+ .addTo(compositeDisposable)
219230 }
220231
221232 override fun bind (item : Item ) {
@@ -231,6 +242,20 @@ class MainAdapter(private val compositeDisposable: CompositeDisposable) :
231242 textError.text = item.error?.message
232243
233244 adapter.submitList(item.items)
245+
246+ layoutManagerSavedState?.let {
247+ linearLayoutManager.onRestoreInstanceState(it)
248+ layoutManagerSavedState = null
249+ }
234250 }
235251 }
252+
253+ override fun onViewRecycled (holder : VH ) {
254+ super .onViewRecycled(holder)
255+ if (holder is HorizontalListVH ) {
256+ layoutManagerSavedState = holder.linearLayoutManager.onSaveInstanceState()
257+ }
258+ }
259+
260+ fun scrollHorizontalListToFirst () = scrollToFirst.onNext(Unit )
236261}
0 commit comments