Remove manual CoroutineScope implementations

This commit is contained in:
William Brawner 2021-02-21 13:57:48 -07:00
parent 7bf4bef8a2
commit eb756e8525
6 changed files with 32 additions and 80 deletions

View file

@ -6,19 +6,18 @@ import android.os.Build
import android.os.Bundle import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.lifecycleScope
import androidx.preference.PreferenceManager import androidx.preference.PreferenceManager
import com.wbrawner.simplemarkdown.R import com.wbrawner.simplemarkdown.R
import com.wbrawner.simplemarkdown.viewmodel.PREF_KEY_AUTOSAVE_URI import com.wbrawner.simplemarkdown.viewmodel.PREF_KEY_AUTOSAVE_URI
import kotlinx.coroutines.* import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext import timber.log.Timber
class SplashActivity : AppCompatActivity(), CoroutineScope { class SplashActivity : AppCompatActivity() {
override val coroutineContext: CoroutineContext = Dispatchers.Main
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
launch { lifecycleScope.launch {
val darkMode = withContext(Dispatchers.IO) { val darkMode = withContext(Dispatchers.IO) {
val darkModeValue = PreferenceManager.getDefaultSharedPreferences(this@SplashActivity) val darkModeValue = PreferenceManager.getDefaultSharedPreferences(this@SplashActivity)
.getString( .getString(
@ -58,11 +57,4 @@ class SplashActivity : AppCompatActivity(), CoroutineScope {
finish() finish()
} }
} }
override fun onDestroy() {
super.onDestroy()
coroutineContext[Job]?.let {
cancel()
}
}
} }

View file

@ -18,6 +18,7 @@ import androidx.core.widget.NestedScrollView
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.preference.PreferenceManager import androidx.preference.PreferenceManager
import com.wbrawner.simplemarkdown.R import com.wbrawner.simplemarkdown.R
import com.wbrawner.simplemarkdown.model.Readability import com.wbrawner.simplemarkdown.model.Readability
@ -26,14 +27,12 @@ import com.wbrawner.simplemarkdown.utility.showKeyboard
import com.wbrawner.simplemarkdown.view.ViewPagerPage import com.wbrawner.simplemarkdown.view.ViewPagerPage
import com.wbrawner.simplemarkdown.viewmodel.MarkdownViewModel import com.wbrawner.simplemarkdown.viewmodel.MarkdownViewModel
import kotlinx.coroutines.* import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
import kotlin.math.abs import kotlin.math.abs
class EditFragment : Fragment(), ViewPagerPage, CoroutineScope { class EditFragment : Fragment(), ViewPagerPage {
private var markdownEditor: EditText? = null private var markdownEditor: EditText? = null
private var markdownEditorScroller: NestedScrollView? = null private var markdownEditorScroller: NestedScrollView? = null
private val viewModel: MarkdownViewModel by viewModels({ requireParentFragment() }) private val viewModel: MarkdownViewModel by viewModels({ requireParentFragment() })
override val coroutineContext: CoroutineContext = Dispatchers.Main
private var readabilityWatcher: TextWatcher? = null private var readabilityWatcher: TextWatcher? = null
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
@ -56,7 +55,7 @@ class EditFragment : Fragment(), ViewPagerPage, CoroutineScope {
searchFor = searchText searchFor = searchText
launch { lifecycleScope.launch {
delay(50) delay(50)
if (searchText != searchFor) if (searchText != searchFor)
return@launch return@launch
@ -101,7 +100,7 @@ class EditFragment : Fragment(), ViewPagerPage, CoroutineScope {
markdownEditor?.setText(it.markdown) markdownEditor?.setText(it.markdown)
} }
}) })
launch { lifecycleScope.launch {
val enableReadability = withContext(Dispatchers.IO) { val enableReadability = withContext(Dispatchers.IO) {
context?.let { context?.let {
PreferenceManager.getDefaultSharedPreferences(it) PreferenceManager.getDefaultSharedPreferences(it)
@ -122,13 +121,6 @@ class EditFragment : Fragment(), ViewPagerPage, CoroutineScope {
} }
} }
override fun onDestroyView() {
coroutineContext[Job]?.let {
cancel()
}
super.onDestroyView()
}
override fun onSelected() { override fun onSelected() {
markdownEditor?.showKeyboard() markdownEditor?.showKeyboard()
} }
@ -148,7 +140,7 @@ class EditFragment : Fragment(), ViewPagerPage, CoroutineScope {
searchFor = searchText searchFor = searchText
launch { lifecycleScope.launch {
delay(250) delay(250)
if (searchText != searchFor) if (searchText != searchFor)
return@launch return@launch

View file

@ -6,10 +6,8 @@ import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.content.res.Configuration import android.content.res.Configuration
import android.net.Uri
import android.os.Build import android.os.Build
import android.os.Bundle import android.os.Bundle
import android.util.Log
import android.view.* import android.view.*
import android.webkit.MimeTypeMap import android.webkit.MimeTypeMap
import android.widget.Toast import android.widget.Toast
@ -21,6 +19,7 @@ import androidx.core.content.edit
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupWithNavController import androidx.navigation.ui.setupWithNavController
@ -33,13 +32,10 @@ import com.wbrawner.simplemarkdown.viewmodel.MarkdownViewModel
import com.wbrawner.simplemarkdown.viewmodel.PREF_KEY_AUTOSAVE_URI import com.wbrawner.simplemarkdown.viewmodel.PREF_KEY_AUTOSAVE_URI
import kotlinx.android.synthetic.main.fragment_main.* import kotlinx.android.synthetic.main.fragment_main.*
import kotlinx.coroutines.* import kotlinx.coroutines.*
import java.io.File import timber.log.Timber
import kotlin.coroutines.CoroutineContext
class MainFragment : Fragment(), ActivityCompat.OnRequestPermissionsResultCallback, CoroutineScope { class MainFragment : Fragment(), ActivityCompat.OnRequestPermissionsResultCallback {
private var shouldAutoSave = true
override val coroutineContext: CoroutineContext = Dispatchers.Main
private val viewModel: MarkdownViewModel by viewModels() private val viewModel: MarkdownViewModel by viewModels()
private var appBarConfiguration: AppBarConfiguration? = null private var appBarConfiguration: AppBarConfiguration? = null
private val errorHandler: ErrorHandler by errorHandlerImpl() private val errorHandler: ErrorHandler by errorHandlerImpl()
@ -47,13 +43,11 @@ class MainFragment : Fragment(), ActivityCompat.OnRequestPermissionsResultCallba
override fun onAttach(context: Context) { override fun onAttach(context: Context) {
super.onAttach(context) super.onAttach(context)
if (context !is Activity) return if (context !is Activity) return
context.intent?.data?.let { lifecycleScope.launch {
launch { viewModel.load(context, context.intent?.data)
viewModel.load(context, it)
context.intent?.data = null context.intent?.data = null
} }
} }
}
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
@ -99,8 +93,8 @@ class MainFragment : Fragment(), ActivityCompat.OnRequestPermissionsResultCallba
true true
} }
R.id.action_save -> { R.id.action_save -> {
launch { Timber.d("Save clicked")
Log.d("SimpleMarkdown", "Saving file from onOptionsItemSelected") lifecycleScope.launch {
if (!viewModel.save(requireContext())) { if (!viewModel.save(requireContext())) {
requestFileOp(REQUEST_SAVE_FILE) requestFileOp(REQUEST_SAVE_FILE)
} else { } else {
@ -146,7 +140,7 @@ class MainFragment : Fragment(), ActivityCompat.OnRequestPermissionsResultCallba
override fun onStart() { override fun onStart() {
super.onStart() super.onStart()
launch { lifecycleScope.launch {
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val enableErrorReports = PreferenceManager.getDefaultSharedPreferences(requireContext()) val enableErrorReports = PreferenceManager.getDefaultSharedPreferences(requireContext())
.getBoolean(getString(R.string.pref_key_error_reports_enabled), true) .getBoolean(getString(R.string.pref_key_error_reports_enabled), true)
@ -158,7 +152,7 @@ class MainFragment : Fragment(), ActivityCompat.OnRequestPermissionsResultCallba
override fun onPause() { override fun onPause() {
super.onPause() super.onPause()
val context = context?.applicationContext ?: return val context = context?.applicationContext ?: return
launch { lifecycleScope.launch {
viewModel.autosave(context, PreferenceManager.getDefaultSharedPreferences(context)) viewModel.autosave(context, PreferenceManager.getDefaultSharedPreferences(context))
} }
} }
@ -200,7 +194,7 @@ class MainFragment : Fragment(), ActivityCompat.OnRequestPermissionsResultCallba
return return
} }
launch { lifecycleScope.launch {
val fileLoaded = context?.let { val fileLoaded = context?.let {
viewModel.load(it, data.data) viewModel.load(it, data.data)
} }
@ -221,7 +215,7 @@ class MainFragment : Fragment(), ActivityCompat.OnRequestPermissionsResultCallba
return return
} }
launch { lifecycleScope.launch {
context?.let { context?.let {
Log.d("SimpleMarkdown", "Saving file from onActivityResult") Log.d("SimpleMarkdown", "Saving file from onActivityResult")
viewModel.save(it, data.data) viewModel.save(it, data.data)
@ -300,13 +294,6 @@ class MainFragment : Fragment(), ActivityCompat.OnRequestPermissionsResultCallba
shouldAutoSave = true shouldAutoSave = true
} }
override fun onDestroy() {
super.onDestroy()
coroutineContext[Job]?.let {
cancel()
}
}
companion object { companion object {
// Request codes // Request codes
const val REQUEST_OPEN_FILE = 1 const val REQUEST_OPEN_FILE = 1

View file

@ -9,6 +9,7 @@ import android.view.ViewGroup
import android.widget.Toast import android.widget.Toast
import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.app.AppCompatDelegate
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.setupWithNavController import androidx.navigation.ui.setupWithNavController
import com.wbrawner.simplemarkdown.R import com.wbrawner.simplemarkdown.R
@ -17,14 +18,9 @@ import com.wbrawner.simplemarkdown.utility.errorHandlerImpl
import com.wbrawner.simplemarkdown.utility.readAssetToString import com.wbrawner.simplemarkdown.utility.readAssetToString
import com.wbrawner.simplemarkdown.utility.toHtml import com.wbrawner.simplemarkdown.utility.toHtml
import kotlinx.android.synthetic.main.fragment_markdown_info.* import kotlinx.android.synthetic.main.fragment_markdown_info.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
class MarkdownInfoFragment : Fragment(), CoroutineScope { class MarkdownInfoFragment : Fragment() {
override val coroutineContext: CoroutineContext = Dispatchers.Main
private val errorHandler: ErrorHandler by errorHandlerImpl() private val errorHandler: ErrorHandler by errorHandlerImpl()
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
@ -52,7 +48,7 @@ class MarkdownInfoFragment : Fragment(), CoroutineScope {
R.string.pref_custom_css_default R.string.pref_custom_css_default
} }
val css: String? = getString(defaultCssId) val css: String? = getString(defaultCssId)
launch { lifecycleScope.launch {
try { try {
val html = view.context.assets?.readAssetToString(fileName) val html = view.context.assets?.readAssetToString(fileName)
?.toHtml() ?.toHtml()
@ -70,12 +66,6 @@ class MarkdownInfoFragment : Fragment(), CoroutineScope {
} }
} }
override fun onDestroy() {
coroutineContext[Job]?.cancel()
super.onDestroy()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean { override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) { if (item.itemId == android.R.id.home) {
findNavController().navigateUp() findNavController().navigateUp()

View file

@ -11,17 +11,15 @@ import android.webkit.WebView
import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.app.AppCompatDelegate
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer import androidx.lifecycle.lifecycleScope
import androidx.preference.PreferenceManager import androidx.preference.PreferenceManager
import com.wbrawner.simplemarkdown.BuildConfig import com.wbrawner.simplemarkdown.BuildConfig
import com.wbrawner.simplemarkdown.R import com.wbrawner.simplemarkdown.R
import com.wbrawner.simplemarkdown.utility.toHtml import com.wbrawner.simplemarkdown.utility.toHtml
import com.wbrawner.simplemarkdown.viewmodel.MarkdownViewModel import com.wbrawner.simplemarkdown.viewmodel.MarkdownViewModel
import kotlinx.coroutines.* import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
class PreviewFragment : Fragment(), CoroutineScope { class PreviewFragment : Fragment() {
override val coroutineContext: CoroutineContext = Dispatchers.Main
private val viewModel: MarkdownViewModel by viewModels({ requireParentFragment() }) private val viewModel: MarkdownViewModel by viewModels({ requireParentFragment() })
private var markdownPreview: WebView? = null private var markdownPreview: WebView? = null
private var style: String = "" private var style: String = ""
@ -35,7 +33,7 @@ class PreviewFragment : Fragment(), CoroutineScope {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
markdownPreview = view.findViewById(R.id.markdown_view) markdownPreview = view.findViewById(R.id.markdown_view)
WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG) WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG)
launch { lifecycleScope.launch {
val isNightMode = AppCompatDelegate.getDefaultNightMode() == val isNightMode = AppCompatDelegate.getDefaultNightMode() ==
AppCompatDelegate.MODE_NIGHT_YES AppCompatDelegate.MODE_NIGHT_YES
|| requireContext().resources.configuration.uiMode and UI_MODE_NIGHT_MASK == UI_MODE_NIGHT_YES || requireContext().resources.configuration.uiMode and UI_MODE_NIGHT_MASK == UI_MODE_NIGHT_YES
@ -64,14 +62,14 @@ class PreviewFragment : Fragment(), CoroutineScope {
override fun onAttach(context: Context) { override fun onAttach(context: Context) {
super.onAttach(context) super.onAttach(context)
updateWebContent(viewModel.markdownUpdates.value ?: "") updateWebContent(viewModel.markdownUpdates.value ?: "")
viewModel.markdownUpdates.observe(this, Observer { viewModel.markdownUpdates.observe(this, {
updateWebContent(it) updateWebContent(it)
}) })
} }
private fun updateWebContent(markdown: String) { private fun updateWebContent(markdown: String) {
markdownPreview?.post { markdownPreview?.post {
launch { lifecycleScope.launch {
markdownPreview?.loadDataWithBaseURL(null, markdownPreview?.loadDataWithBaseURL(null,
style + markdown.toHtml(), style + markdown.toHtml(),
"text/html", "text/html",
@ -82,9 +80,6 @@ class PreviewFragment : Fragment(), CoroutineScope {
} }
override fun onDestroyView() { override fun onDestroyView() {
coroutineContext[Job]?.let {
cancel()
}
markdownPreview?.let { markdownPreview?.let {
(it.parent as ViewGroup).removeView(it) (it.parent as ViewGroup).removeView(it)
it.destroy() it.destroy()

View file

@ -4,21 +4,19 @@ import android.content.SharedPreferences
import android.os.Build import android.os.Build
import android.os.Bundle import android.os.Bundle
import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.lifecycleScope
import androidx.preference.ListPreference import androidx.preference.ListPreference
import androidx.preference.Preference import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceManager import androidx.preference.PreferenceManager
import com.wbrawner.simplemarkdown.BuildConfig import com.wbrawner.simplemarkdown.BuildConfig
import com.wbrawner.simplemarkdown.R import com.wbrawner.simplemarkdown.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
class SettingsFragment class SettingsFragment
: PreferenceFragmentCompat(), : PreferenceFragmentCompat(),
SharedPreferences.OnSharedPreferenceChangeListener, SharedPreferences.OnSharedPreferenceChangeListener {
CoroutineScope {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.pref_general) addPreferencesFromResource(R.xml.pref_general)
if (BuildConfig.DEBUG) { if (BuildConfig.DEBUG) {
@ -31,11 +29,9 @@ class SettingsFragment
} }
} }
override val coroutineContext: CoroutineContext = Dispatchers.Main
override fun onActivityCreated(savedInstanceState: Bundle?) { override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState) super.onActivityCreated(savedInstanceState)
launch(context = Dispatchers.IO) { lifecycleScope.launch(context = Dispatchers.IO) {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity) val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
sharedPreferences.registerOnSharedPreferenceChangeListener(this@SettingsFragment) sharedPreferences.registerOnSharedPreferenceChangeListener(this@SettingsFragment)
(findPreference(getString(R.string.pref_key_dark_mode)) as? ListPreference)?.let { (findPreference(getString(R.string.pref_key_dark_mode)) as? ListPreference)?.let {