Skip to content

Commit

Permalink
Observe filter data on onResume and dispose it on onPause
Browse files Browse the repository at this point in the history
This prevents the case where the IllegalStateException is thrown
as a result of fragment not being attached to the context at the
time subscribe callback gets run.
  • Loading branch information
darshanparajuli committed Aug 19, 2018
1 parent fd7b0fe commit 8530593
Showing 1 changed file with 28 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.dp.logcatapp.fragments.filters

import android.annotation.SuppressLint
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v7.util.DiffUtil
Expand All @@ -19,6 +20,7 @@ import com.dp.logcatapp.fragments.logcatlive.LogcatLiveViewModel
import com.dp.logcatapp.util.inflateLayout
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

class FiltersFragment : BaseFragment() {
Expand All @@ -40,6 +42,7 @@ class FiltersFragment : BaseFragment() {
private lateinit var recyclerViewAdapter: MyRecyclerViewAdapter
private lateinit var linearLayoutManager: LinearLayoutManager
private lateinit var emptyMessage: TextView
private var filterObserver: Disposable? = null

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Expand All @@ -49,15 +52,16 @@ class FiltersFragment : BaseFragment() {
recyclerViewAdapter = MyRecyclerViewAdapter {
onRemoveClicked(it)
}
}

val dao = MyDB.getInstance(activity!!).filterDao()
private fun startObservingFilters() {
val dao = MyDB.getInstance(context!!).filterDao()
val flowable = if (isExclusions()) {
dao.getExclusions()
} else {
dao.getFilters()
}

flowable.observeOn(AndroidSchedulers.mainThread())
filterObserver = flowable.observeOn(AndroidSchedulers.mainThread())
.subscribe { list ->
val data = list.map {
val displayText: String
Expand Down Expand Up @@ -102,8 +106,28 @@ class FiltersFragment : BaseFragment() {
}
}

private fun stopObservingFilters() {
filterObserver?.let {
if (!it.isDisposed) {
it.dispose()
}
}
filterObserver = null
}

override fun onResume() {
super.onResume()
startObservingFilters()
}

override fun onPause() {
super.onPause()
stopObservingFilters()
}

fun isExclusions() = arguments?.getBoolean(KEY_EXCLUSIONS) ?: false

@SuppressLint("CheckResult")
private fun onRemoveClicked(v: View) {
val pos = linearLayoutManager.getPosition(v)
if (pos != RecyclerView.NO_POSITION) {
Expand Down Expand Up @@ -158,6 +182,7 @@ class FiltersFragment : BaseFragment() {
}
}

@SuppressLint("CheckResult")
fun addFilter(keyword: String, tag: String, pid: String, tid: String, logLevels: Set<String>) {
val list = mutableListOf<FilterInfo>()
val exclude = isExclusions()
Expand Down

0 comments on commit 8530593

Please sign in to comment.