Skip to content

Commit

Permalink
Part 8: Saving news in onSavedInstanceState
Browse files Browse the repository at this point in the history
  • Loading branch information
juanchosaravia committed Apr 29, 2016
1 parent d4dabc4 commit f6c837a
Showing 1 changed file with 24 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ import rx.schedulers.Schedulers

class NewsFragment : RxBaseFragment() {

companion object {
private val KEY_REDDIT_NEWS = "redditNews"
}

private var redditNews: RedditNews? = null
private val newsManager by lazy { NewsManager() }

Expand All @@ -28,18 +32,32 @@ class NewsFragment : RxBaseFragment() {
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)

news_list.setHasFixedSize(true)
val linearLayout = LinearLayoutManager(context)
news_list.layoutManager = linearLayout
news_list.clearOnScrollListeners()
news_list.addOnScrollListener(InfiniteScrollListener({ requestNews() }, linearLayout))
news_list.apply {
setHasFixedSize(true)
val linearLayout = LinearLayoutManager(context)
layoutManager = linearLayout
clearOnScrollListeners()
addOnScrollListener(InfiniteScrollListener({ requestNews() }, linearLayout))
}

initAdapter()

if (savedInstanceState == null) {
if (savedInstanceState != null && savedInstanceState.containsKey(KEY_REDDIT_NEWS)) {
redditNews = savedInstanceState.get(KEY_REDDIT_NEWS) as RedditNews
(news_list.adapter as NewsAdapter).clearAndAddNews(redditNews!!.news)
} else {
requestNews()
}
}

override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
val news = (news_list.adapter as NewsAdapter).getNews()
if (redditNews != null && news.size > 0) {
outState.putParcelable(KEY_REDDIT_NEWS, redditNews?.copy(news = news))
}
}

private fun requestNews() {
/**
* first time will send empty string for after parameter.
Expand Down

0 comments on commit f6c837a

Please sign in to comment.