11package me.alllexey123.itmowidgets.ui.schedule
22
33import android.os.Bundle
4+ import android.os.Parcelable
45import android.view.View
56import android.widget.ProgressBar
67import android.widget.Toast
@@ -18,6 +19,8 @@ class ScheduleActivity : AppCompatActivity() {
1819 private lateinit var dayScheduleAdapter: DayScheduleAdapter
1920 private lateinit var progressBar: ProgressBar
2021
22+ private val snapHelper = PagerSnapHelper ()
23+
2124 private val scheduleViewModel: ScheduleViewModel by viewModels {
2225 val appContainer = (application as ItmoWidgetsApp ).appContainer
2326 ScheduleViewModelFactory (appContainer.scheduleRepository)
@@ -43,10 +46,13 @@ class ScheduleActivity : AppCompatActivity() {
4346 dayScheduleAdapter = DayScheduleAdapter (listOf ())
4447 outerRecyclerView.adapter = dayScheduleAdapter
4548
46- val snapHelper = PagerSnapHelper ()
4749 snapHelper.attachToRecyclerView(outerRecyclerView)
4850 }
4951
52+ private var isInitialLoad = true
53+
54+ private var layoutManagerState: Parcelable ? = null
55+
5056 private fun observeUiState () {
5157 scheduleViewModel.uiState.observe(this ) { state ->
5258 when (state) {
@@ -57,22 +63,35 @@ class ScheduleActivity : AppCompatActivity() {
5763
5864 is ScheduleUiState .Success -> {
5965 val scheduleList = state.schedule
60- dayScheduleAdapter.updateData(scheduleList)
66+ if (scheduleList.isEmpty()) {
67+ outerRecyclerView.visibility = View .GONE
68+ progressBar.visibility = View .GONE
69+ return @observe
70+ }
6171
62- if (state.isCached) {
63- progressBar.visibility = View .VISIBLE
72+ val layoutManager = outerRecyclerView.layoutManager as LinearLayoutManager
73+ if (! isInitialLoad) {
74+ layoutManagerState = layoutManager.onSaveInstanceState()
75+ }
6476
65- // scroll if cached
77+ dayScheduleAdapter.updateData(scheduleList)
78+
79+ if (isInitialLoad) {
6680 val today = LocalDate .now()
6781 val todayIndex = scheduleList.indexOfFirst { it.date == today }
6882 if (todayIndex != - 1 ) {
69- val layoutManager =
70- outerRecyclerView.layoutManager as LinearLayoutManager
7183 layoutManager.scrollToPositionWithOffset(todayIndex, 0 )
7284 }
73- } else {
74- progressBar.visibility = View .GONE
85+ isInitialLoad = false
86+ } else if (layoutManagerState != null ) {
87+ layoutManager.onRestoreInstanceState(layoutManagerState)
7588 }
89+
90+ if (scheduleList.isNotEmpty()) {
91+ isInitialLoad = false
92+ }
93+
94+ progressBar.visibility = if (state.isCached) View .VISIBLE else View .GONE
7695 outerRecyclerView.visibility = View .VISIBLE
7796 }
7897
0 commit comments