pull/1155/head
gedoor 3 years ago
parent a2f2b8289f
commit df077da03f
  1. 11
      app/src/main/java/io/legado/app/base/BaseActivity.kt
  2. 20
      app/src/main/java/io/legado/app/base/BaseDialogFragment.kt
  3. 31
      app/src/main/java/io/legado/app/base/BaseFragment.kt
  4. 13
      app/src/main/java/io/legado/app/base/BaseViewModel.kt
  5. 11
      app/src/main/java/io/legado/app/data/dao/BookGroupDao.kt
  6. 5
      app/src/main/java/io/legado/app/ui/about/ReadRecordActivity.kt
  7. 15
      app/src/main/java/io/legado/app/ui/book/arrange/ArrangeBookActivity.kt
  8. 17
      app/src/main/java/io/legado/app/ui/book/cache/CacheActivity.kt
  9. 3
      app/src/main/java/io/legado/app/ui/book/changecover/ChangeCoverViewModel.kt
  10. 3
      app/src/main/java/io/legado/app/ui/book/changesource/ChangeSourceDialog.kt
  11. 7
      app/src/main/java/io/legado/app/ui/book/changesource/ChangeSourceViewModel.kt
  12. 3
      app/src/main/java/io/legado/app/ui/book/explore/ExploreShowViewModel.kt
  13. 9
      app/src/main/java/io/legado/app/ui/book/group/GroupManageDialog.kt
  14. 9
      app/src/main/java/io/legado/app/ui/book/group/GroupSelectDialog.kt
  15. 3
      app/src/main/java/io/legado/app/ui/book/info/BookInfoActivity.kt
  16. 11
      app/src/main/java/io/legado/app/ui/book/local/ImportBookActivity.kt
  17. 15
      app/src/main/java/io/legado/app/ui/book/read/ReadBookActivity.kt
  18. 5
      app/src/main/java/io/legado/app/ui/book/read/ReadBookViewModel.kt
  19. 7
      app/src/main/java/io/legado/app/ui/book/read/config/TocRegexDialog.kt
  20. 7
      app/src/main/java/io/legado/app/ui/book/search/SearchActivity.kt
  21. 5
      app/src/main/java/io/legado/app/ui/book/search/SearchViewModel.kt
  22. 5
      app/src/main/java/io/legado/app/ui/book/searchContent/SearchContentActivity.kt
  23. 3
      app/src/main/java/io/legado/app/ui/book/source/debug/BookSourceDebugActivity.kt
  24. 5
      app/src/main/java/io/legado/app/ui/book/source/manage/BookSourceActivity.kt
  25. 3
      app/src/main/java/io/legado/app/ui/book/source/manage/GroupManageDialog.kt
  26. 3
      app/src/main/java/io/legado/app/ui/book/toc/BookmarkFragment.kt
  27. 7
      app/src/main/java/io/legado/app/ui/book/toc/ChapterListFragment.kt
  28. 10
      app/src/main/java/io/legado/app/ui/main/bookshelf/style1/BookshelfFragment1.kt
  29. 3
      app/src/main/java/io/legado/app/ui/main/bookshelf/style1/books/BooksFragment.kt
  30. 8
      app/src/main/java/io/legado/app/ui/main/bookshelf/style2/BookshelfFragment2.kt
  31. 7
      app/src/main/java/io/legado/app/ui/main/explore/ExploreFragment.kt
  32. 5
      app/src/main/java/io/legado/app/ui/main/rss/RssFragment.kt
  33. 3
      app/src/main/java/io/legado/app/ui/rss/article/RssArticlesFragment.kt
  34. 5
      app/src/main/java/io/legado/app/ui/rss/article/RssArticlesViewModel.kt
  35. 3
      app/src/main/java/io/legado/app/ui/rss/favorites/RssFavoritesActivity.kt
  36. 3
      app/src/main/java/io/legado/app/ui/rss/read/ReadRssActivity.kt
  37. 6
      app/src/main/java/io/legado/app/ui/rss/read/ReadRssViewModel.kt
  38. 3
      app/src/main/java/io/legado/app/ui/rss/source/debug/RssSourceDebugActivity.kt
  39. 3
      app/src/main/java/io/legado/app/ui/rss/source/debug/RssSourceDebugModel.kt
  40. 3
      app/src/main/java/io/legado/app/ui/rss/source/manage/GroupManageDialog.kt
  41. 5
      app/src/main/java/io/legado/app/ui/rss/source/manage/RssSourceActivity.kt
  42. 9
      app/src/main/java/io/legado/app/ui/rss/subscription/RuleSubActivity.kt
  43. 3
      app/src/main/java/io/legado/app/ui/widget/dialog/TextDialog.kt
  44. 3
      app/src/main/java/io/legado/app/ui/widget/font/FontSelectDialog.kt

@ -24,9 +24,6 @@ import io.legado.app.lib.theme.backgroundColor
import io.legado.app.lib.theme.primaryColor import io.legado.app.lib.theme.primaryColor
import io.legado.app.ui.widget.TitleBar import io.legado.app.ui.widget.TitleBar
import io.legado.app.utils.* import io.legado.app.utils.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
abstract class BaseActivity<VB : ViewBinding>( abstract class BaseActivity<VB : ViewBinding>(
@ -35,8 +32,7 @@ abstract class BaseActivity<VB : ViewBinding>(
private val toolBarTheme: Theme = Theme.Auto, private val toolBarTheme: Theme = Theme.Auto,
private val transparent: Boolean = false, private val transparent: Boolean = false,
private val imageBg: Boolean = true private val imageBg: Boolean = true
) : AppCompatActivity(), ) : AppCompatActivity() {
CoroutineScope by MainScope() {
protected abstract val binding: VB protected abstract val binding: VB
@ -120,11 +116,6 @@ abstract class BaseActivity<VB : ViewBinding>(
setupSystemBar() setupSystemBar()
} }
override fun onDestroy() {
super.onDestroy()
cancel()
}
abstract fun onActivityCreated(savedInstanceState: Bundle?) abstract fun onActivityCreated(savedInstanceState: Bundle?)
final override fun onCreateOptionsMenu(menu: Menu?): Boolean { final override fun onCreateOptionsMenu(menu: Menu?): Boolean {

@ -4,23 +4,14 @@ import android.os.Bundle
import android.view.View import android.view.View
import androidx.fragment.app.DialogFragment import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentManager
import androidx.lifecycle.lifecycleScope
import io.legado.app.help.coroutine.Coroutine import io.legado.app.help.coroutine.Coroutine
import io.legado.app.lib.theme.ThemeStore import io.legado.app.lib.theme.ThemeStore
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlin.coroutines.CoroutineContext import kotlin.coroutines.CoroutineContext
abstract class BaseDialogFragment : DialogFragment() {
abstract class BaseDialogFragment : DialogFragment(), CoroutineScope {
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
private lateinit var job: Job
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
job = Job()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
@ -39,13 +30,8 @@ abstract class BaseDialogFragment : DialogFragment(), CoroutineScope {
} }
} }
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
fun <T> execute( fun <T> execute(
scope: CoroutineScope = this, scope: CoroutineScope = lifecycleScope,
context: CoroutineContext = Dispatchers.IO, context: CoroutineContext = Dispatchers.IO,
block: suspend CoroutineScope.() -> T block: suspend CoroutineScope.() -> T
) = Coroutine.async(scope, context) { block() } ) = Coroutine.async(scope, context) { block() }

@ -3,22 +3,20 @@ package io.legado.app.base
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.content.res.Configuration import android.content.res.Configuration
import android.os.Bundle import android.os.Bundle
import android.view.* import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.appcompat.view.SupportMenuInflater import androidx.appcompat.view.SupportMenuInflater
import androidx.appcompat.widget.Toolbar import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import io.legado.app.R import io.legado.app.R
import io.legado.app.ui.widget.TitleBar import io.legado.app.ui.widget.TitleBar
import io.legado.app.utils.applyTint import io.legado.app.utils.applyTint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlin.coroutines.CoroutineContext
@Suppress("MemberVisibilityCanBePrivate") @Suppress("MemberVisibilityCanBePrivate")
abstract class BaseFragment(layoutID: Int) : Fragment(layoutID), abstract class BaseFragment(layoutID: Int) : Fragment(layoutID) {
CoroutineScope {
lateinit var job: Job
var supportToolbar: Toolbar? = null var supportToolbar: Toolbar? = null
private set private set
@ -26,18 +24,6 @@ abstract class BaseFragment(layoutID: Int) : Fragment(layoutID),
@SuppressLint("RestrictedApi") @SuppressLint("RestrictedApi")
get() = SupportMenuInflater(requireContext()) get() = SupportMenuInflater(requireContext())
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
job = Job()
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
onMultiWindowModeChanged() onMultiWindowModeChanged()
@ -64,11 +50,6 @@ abstract class BaseFragment(layoutID: Int) : Fragment(layoutID),
} }
} }
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
fun setSupportToolbar(toolbar: Toolbar) { fun setSupportToolbar(toolbar: Toolbar) {
supportToolbar = toolbar supportToolbar = toolbar
supportToolbar?.let { supportToolbar?.let {

@ -4,20 +4,22 @@ import android.app.Application
import android.content.Context import android.content.Context
import androidx.annotation.CallSuper import androidx.annotation.CallSuper
import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import io.legado.app.App import io.legado.app.App
import io.legado.app.help.coroutine.Coroutine import io.legado.app.help.coroutine.Coroutine
import io.legado.app.utils.toastOnUi import io.legado.app.utils.toastOnUi
import kotlinx.coroutines.* import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlin.coroutines.CoroutineContext import kotlin.coroutines.CoroutineContext
@Suppress("unused") @Suppress("unused")
open class BaseViewModel(application: Application) : AndroidViewModel(application), open class BaseViewModel(application: Application) : AndroidViewModel(application) {
CoroutineScope by MainScope() {
val context: Context by lazy { this.getApplication<App>() } val context: Context by lazy { this.getApplication<App>() }
fun <T> execute( fun <T> execute(
scope: CoroutineScope = this, scope: CoroutineScope = viewModelScope,
context: CoroutineContext = Dispatchers.IO, context: CoroutineContext = Dispatchers.IO,
block: suspend CoroutineScope.() -> T block: suspend CoroutineScope.() -> T
): Coroutine<T> { ): Coroutine<T> {
@ -25,7 +27,7 @@ open class BaseViewModel(application: Application) : AndroidViewModel(applicatio
} }
fun <R> submit( fun <R> submit(
scope: CoroutineScope = this, scope: CoroutineScope = viewModelScope,
context: CoroutineContext = Dispatchers.IO, context: CoroutineContext = Dispatchers.IO,
block: suspend CoroutineScope.() -> Deferred<R> block: suspend CoroutineScope.() -> Deferred<R>
): Coroutine<R> { ): Coroutine<R> {
@ -35,7 +37,6 @@ open class BaseViewModel(application: Application) : AndroidViewModel(applicatio
@CallSuper @CallSuper
override fun onCleared() { override fun onCleared() {
super.onCleared() super.onCleared()
cancel()
} }
open fun toastOnUi(message: Int) { open fun toastOnUi(message: Int) {

@ -1,9 +1,9 @@
package io.legado.app.data.dao package io.legado.app.data.dao
import androidx.lifecycle.LiveData
import androidx.room.* import androidx.room.*
import io.legado.app.constant.BookType import io.legado.app.constant.BookType
import io.legado.app.data.entities.BookGroup import io.legado.app.data.entities.BookGroup
import kotlinx.coroutines.flow.Flow
@Dao @Dao
interface BookGroupDao { interface BookGroupDao {
@ -15,7 +15,7 @@ interface BookGroupDao {
fun getByName(groupName: String): BookGroup? fun getByName(groupName: String): BookGroup?
@Query("SELECT * FROM book_groups ORDER BY `order`") @Query("SELECT * FROM book_groups ORDER BY `order`")
fun liveDataAll(): LiveData<List<BookGroup>> fun liveDataAll(): Flow<List<BookGroup>>
@Query( @Query(
""" """
@ -24,13 +24,12 @@ interface BookGroupDao {
or (groupId = -3 and show > 0 and (select count(bookUrl) from books where type = ${BookType.audio}) > 0) or (groupId = -3 and show > 0 and (select count(bookUrl) from books where type = ${BookType.audio}) > 0)
or (groupId = -2 and show > 0 and (select count(bookUrl) from books where origin = '${BookType.local}') > 0) or (groupId = -2 and show > 0 and (select count(bookUrl) from books where origin = '${BookType.local}') > 0)
or (groupId = -1 and show > 0) or (groupId = -1 and show > 0)
ORDER BY `order` ORDER BY `order`"""
"""
) )
fun liveDataShow(): LiveData<List<BookGroup>> fun liveDataShow(): Flow<List<BookGroup>>
@Query("SELECT * FROM book_groups where groupId >= 0 ORDER BY `order`") @Query("SELECT * FROM book_groups where groupId >= 0 ORDER BY `order`")
fun liveDataSelect(): LiveData<List<BookGroup>> fun liveDataSelect(): Flow<List<BookGroup>>
@get:Query("SELECT sum(groupId) FROM book_groups where groupId >= 0") @get:Query("SELECT sum(groupId) FROM book_groups where groupId >= 0")
val idsSum: Long val idsSum: Long

@ -5,6 +5,7 @@ import android.os.Bundle
import android.view.Menu import android.view.Menu
import android.view.MenuItem import android.view.MenuItem
import android.view.ViewGroup import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.BaseActivity import io.legado.app.base.BaseActivity
import io.legado.app.base.adapter.ItemViewHolder import io.legado.app.base.adapter.ItemViewHolder
@ -72,7 +73,7 @@ class ReadRecordActivity : BaseActivity<ActivityReadRecordBinding>() {
} }
private fun initData() { private fun initData() {
launch(IO) { lifecycleScope.launch(IO) {
val allTime = appDb.readRecordDao.allTime val allTime = appDb.readRecordDao.allTime
withContext(Main) { withContext(Main) {
binding.readRecord.tvReadTime.text = formatDuring(allTime) binding.readRecord.tvReadTime.text = formatDuring(allTime)
@ -115,7 +116,7 @@ class ReadRecordActivity : BaseActivity<ActivityReadRecordBinding>() {
binding.apply { binding.apply {
root.setOnClickListener { root.setOnClickListener {
val item = getItem(holder.layoutPosition) ?: return@setOnClickListener val item = getItem(holder.layoutPosition) ?: return@setOnClickListener
launch { lifecycleScope.launch {
val book = withContext(IO) { val book = withContext(IO) {
appDb.bookDao.findByName(item.bookName).firstOrNull() appDb.bookDao.findByName(item.bookName).firstOrNull()
} }

@ -5,7 +5,7 @@ import android.view.Menu
import android.view.MenuItem import android.view.MenuItem
import androidx.activity.viewModels import androidx.activity.viewModels
import androidx.appcompat.widget.PopupMenu import androidx.appcompat.widget.PopupMenu
import androidx.lifecycle.LiveData import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import io.legado.app.R import io.legado.app.R
@ -46,14 +46,13 @@ class ArrangeBookActivity : VMBaseActivity<ActivityArrangeBookBinding, ArrangeBo
private val groupRequestCode = 22 private val groupRequestCode = 22
private val addToGroupRequestCode = 34 private val addToGroupRequestCode = 34
private lateinit var adapter: ArrangeBookAdapter private lateinit var adapter: ArrangeBookAdapter
private var groupLiveData: LiveData<List<BookGroup>>? = null
private var booksFlowJob: Job? = null private var booksFlowJob: Job? = null
private var menu: Menu? = null private var menu: Menu? = null
private var groupId: Long = -1 private var groupId: Long = -1
override fun onActivityCreated(savedInstanceState: Bundle?) { override fun onActivityCreated(savedInstanceState: Bundle?) {
groupId = intent.getLongExtra("groupId", -1) groupId = intent.getLongExtra("groupId", -1)
launch { lifecycleScope.launch {
binding.titleBar.subtitle = withContext(IO) { binding.titleBar.subtitle = withContext(IO) {
appDb.bookGroupDao.getByID(groupId)?.groupName appDb.bookGroupDao.getByID(groupId)?.groupName
?: getString(R.string.no_group) ?: getString(R.string.no_group)
@ -109,19 +108,19 @@ class ArrangeBookActivity : VMBaseActivity<ActivityArrangeBookBinding, ArrangeBo
} }
private fun initGroupData() { private fun initGroupData() {
groupLiveData?.removeObservers(this) lifecycleScope.launch {
groupLiveData = appDb.bookGroupDao.liveDataAll() appDb.bookGroupDao.liveDataAll().collect {
groupLiveData?.observe(this, {
groupList.clear() groupList.clear()
groupList.addAll(it) groupList.addAll(it)
adapter.notifyDataSetChanged() adapter.notifyDataSetChanged()
upMenu() upMenu()
}) }
}
} }
private fun initBookData() { private fun initBookData() {
booksFlowJob?.cancel() booksFlowJob?.cancel()
booksFlowJob = launch { booksFlowJob = lifecycleScope.launch {
when (groupId) { when (groupId) {
AppConst.bookGroupAllId -> appDb.bookDao.observeAll() AppConst.bookGroupAllId -> appDb.bookDao.observeAll()
AppConst.bookGroupLocalId -> appDb.bookDao.observeLocal() AppConst.bookGroupLocalId -> appDb.bookDao.observeLocal()

@ -4,7 +4,7 @@ import android.os.Bundle
import android.view.Menu import android.view.Menu
import android.view.MenuItem import android.view.MenuItem
import androidx.activity.viewModels import androidx.activity.viewModels
import androidx.lifecycle.LiveData import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.snackbar.Snackbar import com.google.android.material.snackbar.Snackbar
import io.legado.app.R import io.legado.app.R
@ -46,7 +46,6 @@ class CacheActivity : VMBaseActivity<ActivityCacheBookBinding, CacheViewModel>()
private val exportBookPathKey = "exportBookPath" private val exportBookPathKey = "exportBookPath"
lateinit var adapter: CacheAdapter lateinit var adapter: CacheAdapter
private var groupLiveData: LiveData<List<BookGroup>>? = null
private var booksFlowJob: Job? = null private var booksFlowJob: Job? = null
private var menu: Menu? = null private var menu: Menu? = null
private var exportPosition = -1 private var exportPosition = -1
@ -68,7 +67,7 @@ class CacheActivity : VMBaseActivity<ActivityCacheBookBinding, CacheViewModel>()
override fun onActivityCreated(savedInstanceState: Bundle?) { override fun onActivityCreated(savedInstanceState: Bundle?) {
groupId = intent.getLongExtra("groupId", -1) groupId = intent.getLongExtra("groupId", -1)
launch { lifecycleScope.launch {
binding.titleBar.subtitle = withContext(IO) { binding.titleBar.subtitle = withContext(IO) {
appDb.bookGroupDao.getByID(groupId)?.groupName appDb.bookGroupDao.getByID(groupId)?.groupName
?: getString(R.string.no_group) ?: getString(R.string.no_group)
@ -150,7 +149,7 @@ class CacheActivity : VMBaseActivity<ActivityCacheBookBinding, CacheViewModel>()
private fun initBookData() { private fun initBookData() {
booksFlowJob?.cancel() booksFlowJob?.cancel()
booksFlowJob = launch { booksFlowJob = lifecycleScope.launch {
when (groupId) { when (groupId) {
AppConst.bookGroupAllId -> appDb.bookDao.observeAll() AppConst.bookGroupAllId -> appDb.bookDao.observeAll()
AppConst.bookGroupLocalId -> appDb.bookDao.observeLocal() AppConst.bookGroupLocalId -> appDb.bookDao.observeLocal()
@ -176,18 +175,18 @@ class CacheActivity : VMBaseActivity<ActivityCacheBookBinding, CacheViewModel>()
} }
private fun initGroupData() { private fun initGroupData() {
groupLiveData?.removeObservers(this) lifecycleScope.launch {
groupLiveData = appDb.bookGroupDao.liveDataAll() appDb.bookGroupDao.liveDataAll().collect {
groupLiveData?.observe(this, {
groupList.clear() groupList.clear()
groupList.addAll(it) groupList.addAll(it)
adapter.notifyDataSetChanged() adapter.notifyDataSetChanged()
upMenu() upMenu()
}) }
}
} }
private fun initCacheSize(books: List<Book>) { private fun initCacheSize(books: List<Book>) {
launch(IO) { lifecycleScope.launch(IO) {
books.forEach { book -> books.forEach { book ->
val chapterCaches = hashSetOf<String>() val chapterCaches = hashSetOf<String>()
val cacheNames = BookHelp.getChapterFiles(book) val cacheNames = BookHelp.getChapterFiles(book)

@ -5,6 +5,7 @@ import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
import androidx.lifecycle.MutableLiveData import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import io.legado.app.base.BaseViewModel import io.legado.app.base.BaseViewModel
import io.legado.app.constant.AppPattern import io.legado.app.constant.AppPattern
import io.legado.app.data.appDb import io.legado.app.data.appDb
@ -102,7 +103,7 @@ class ChangeCoverViewModel(application: Application) : BaseViewModel(application
return return
} }
val task = WebBook(source) val task = WebBook(source)
.searchBook(this, name, context = searchPool!!) .searchBook(viewModelScope, name, context = searchPool!!)
.timeout(60000L) .timeout(60000L)
.onSuccess(Dispatchers.IO) { .onSuccess(Dispatchers.IO) {
if (it.isNotEmpty()) { if (it.isNotEmpty()) {

@ -6,6 +6,7 @@ import androidx.appcompat.widget.SearchView
import androidx.appcompat.widget.Toolbar import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentManager
import androidx.fragment.app.viewModels import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import io.legado.app.R import io.legado.app.R
@ -150,7 +151,7 @@ class ChangeSourceDialog : BaseDialogFragment(),
viewModel.searchBooksLiveData.observe(viewLifecycleOwner, { viewModel.searchBooksLiveData.observe(viewLifecycleOwner, {
adapter.setItems(it) adapter.setItems(it)
}) })
launch { lifecycleScope.launch {
appDb.bookSourceDao.liveGroupEnabled().collect { appDb.bookSourceDao.liveGroupEnabled().collect {
groups.clear() groups.clear()
it.map { group -> it.map { group ->

@ -5,6 +5,7 @@ import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
import androidx.lifecycle.MutableLiveData import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import io.legado.app.base.BaseViewModel import io.legado.app.base.BaseViewModel
import io.legado.app.constant.AppPattern import io.legado.app.constant.AppPattern
import io.legado.app.constant.PreferKey import io.legado.app.constant.PreferKey
@ -129,7 +130,7 @@ class ChangeSourceViewModel(application: Application) : BaseViewModel(applicatio
val source = bookSourceList[searchIndex] val source = bookSourceList[searchIndex]
val webBook = WebBook(source) val webBook = WebBook(source)
val task = webBook val task = webBook
.searchBook(this, name, context = searchPool!!) .searchBook(viewModelScope, name, context = searchPool!!)
.timeout(60000L) .timeout(60000L)
.onSuccess(IO) { .onSuccess(IO) {
it.forEach { searchBook -> it.forEach { searchBook ->
@ -168,7 +169,7 @@ class ChangeSourceViewModel(application: Application) : BaseViewModel(applicatio
} }
private fun loadBookInfo(webBook: WebBook, book: Book) { private fun loadBookInfo(webBook: WebBook, book: Book) {
webBook.getBookInfo(this, book) webBook.getBookInfo(viewModelScope, book)
.onSuccess { .onSuccess {
if (context.getPrefBoolean(PreferKey.changeSourceLoadToc)) { if (context.getPrefBoolean(PreferKey.changeSourceLoadToc)) {
loadBookToc(webBook, book) loadBookToc(webBook, book)
@ -184,7 +185,7 @@ class ChangeSourceViewModel(application: Application) : BaseViewModel(applicatio
} }
private fun loadBookToc(webBook: WebBook, book: Book) { private fun loadBookToc(webBook: WebBook, book: Book) {
webBook.getChapterList(this, book) webBook.getChapterList(viewModelScope, book)
.onSuccess(IO) { chapters -> .onSuccess(IO) { chapters ->
if (chapters.isNotEmpty()) { if (chapters.isNotEmpty()) {
book.latestChapterTitle = chapters.last().title book.latestChapterTitle = chapters.last().title

@ -3,6 +3,7 @@ package io.legado.app.ui.book.explore
import android.app.Application import android.app.Application
import android.content.Intent import android.content.Intent
import androidx.lifecycle.MutableLiveData import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import io.legado.app.base.BaseViewModel import io.legado.app.base.BaseViewModel
import io.legado.app.data.appDb import io.legado.app.data.appDb
import io.legado.app.data.entities.BookSource import io.legado.app.data.entities.BookSource
@ -34,7 +35,7 @@ class ExploreShowViewModel(application: Application) : BaseViewModel(application
val source = bookSource val source = bookSource
val url = exploreUrl val url = exploreUrl
if (source != null && url != null) { if (source != null && url != null) {
WebBook(source).exploreBook(this, url, page) WebBook(source).exploreBook(viewModelScope, url, page)
.timeout(30000L) .timeout(30000L)
.onSuccess(IO) { searchBooks -> .onSuccess(IO) { searchBooks ->
booksData.postValue(searchBooks) booksData.postValue(searchBooks)

@ -9,6 +9,7 @@ import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import androidx.appcompat.widget.Toolbar import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.viewModels import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
@ -32,6 +33,8 @@ import io.legado.app.utils.getSize
import io.legado.app.utils.requestInputMethod import io.legado.app.utils.requestInputMethod
import io.legado.app.utils.viewbindingdelegate.viewBinding import io.legado.app.utils.viewbindingdelegate.viewBinding
import io.legado.app.utils.visible import io.legado.app.utils.visible
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
class GroupManageDialog : BaseDialogFragment(), Toolbar.OnMenuItemClickListener { class GroupManageDialog : BaseDialogFragment(), Toolbar.OnMenuItemClickListener {
@ -77,9 +80,11 @@ class GroupManageDialog : BaseDialogFragment(), Toolbar.OnMenuItemClickListener
} }
private fun initData() { private fun initData() {
appDb.bookGroupDao.liveDataAll().observe(viewLifecycleOwner, { lifecycleScope.launch {
appDb.bookGroupDao.liveDataAll().collect {
adapter.setItems(it) adapter.setItems(it)
}) }
}
} }
private fun initMenu() { private fun initMenu() {

@ -10,6 +10,7 @@ import android.view.ViewGroup
import androidx.appcompat.widget.Toolbar import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentManager
import androidx.fragment.app.viewModels import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
@ -32,6 +33,8 @@ import io.legado.app.utils.applyTint
import io.legado.app.utils.getSize import io.legado.app.utils.getSize
import io.legado.app.utils.requestInputMethod import io.legado.app.utils.requestInputMethod
import io.legado.app.utils.viewbindingdelegate.viewBinding import io.legado.app.utils.viewbindingdelegate.viewBinding
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
class GroupSelectDialog : BaseDialogFragment(), Toolbar.OnMenuItemClickListener { class GroupSelectDialog : BaseDialogFragment(), Toolbar.OnMenuItemClickListener {
@ -105,9 +108,11 @@ class GroupSelectDialog : BaseDialogFragment(), Toolbar.OnMenuItemClickListener
} }
private fun initData() { private fun initData() {
appDb.bookGroupDao.liveDataSelect().observe(viewLifecycleOwner, { lifecycleScope.launch {
appDb.bookGroupDao.liveDataSelect().collect {
adapter.setItems(it) adapter.setItems(it)
}) }
}
} }
override fun onMenuItemClick(item: MenuItem?): Boolean { override fun onMenuItemClick(item: MenuItem?): Boolean {

@ -10,6 +10,7 @@ import android.widget.CheckBox
import android.widget.LinearLayout import android.widget.LinearLayout
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.RequestBuilder import com.bumptech.glide.RequestBuilder
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions.bitmapTransform import com.bumptech.glide.request.RequestOptions.bitmapTransform
@ -53,7 +54,7 @@ class BookInfoActivity :
private val tocActivityResult = registerForActivityResult(TocActivityResult()) { private val tocActivityResult = registerForActivityResult(TocActivityResult()) {
it?.let { it?.let {
viewModel.bookData.value?.let { book -> viewModel.bookData.value?.let { book ->
launch { lifecycleScope.launch {
withContext(IO) { withContext(IO) {
viewModel.durChapterIndex = it.first viewModel.durChapterIndex = it.first
book.durChapterIndex = it.first book.durChapterIndex = it.first

@ -9,6 +9,7 @@ import android.view.MenuItem
import androidx.activity.viewModels import androidx.activity.viewModels
import androidx.appcompat.widget.PopupMenu import androidx.appcompat.widget.PopupMenu
import androidx.documentfile.provider.DocumentFile import androidx.documentfile.provider.DocumentFile
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.VMBaseActivity import io.legado.app.base.VMBaseActivity
@ -124,7 +125,7 @@ class ImportBookActivity : VMBaseActivity<ActivityImportBookBinding, ImportBookV
} }
private fun initData() { private fun initData() {
launch { lifecycleScope.launch {
appDb.bookDao.observeLocalUri().collect { appDb.bookDao.observeLocalUri().collect {
adapter.upBookHas(it) adapter.upBookHas(it)
} }
@ -187,7 +188,7 @@ class ImportBookActivity : VMBaseActivity<ActivityImportBookBinding, ImportBookV
binding.tvPath.text = path binding.tvPath.text = path
adapter.selectedUris.clear() adapter.selectedUris.clear()
adapter.clearItems() adapter.clearItems()
launch(IO) { lifecycleScope.launch(IO) {
val docList = DocumentUtils.listFiles(this@ImportBookActivity, lastDoc.uri) val docList = DocumentUtils.listFiles(this@ImportBookActivity, lastDoc.uri)
for (i in docList.lastIndex downTo 0) { for (i in docList.lastIndex downTo 0) {
val item = docList[i] val item = docList[i]
@ -251,7 +252,7 @@ class ImportBookActivity : VMBaseActivity<ActivityImportBookBinding, ImportBookV
adapter.clearItems() adapter.clearItems()
val lastDoc = subDocs.lastOrNull() ?: doc val lastDoc = subDocs.lastOrNull() ?: doc
binding.refreshProgressBar.isAutoLoading = true binding.refreshProgressBar.isAutoLoading = true
launch(IO) { lifecycleScope.launch(IO) {
viewModel.scanDoc(lastDoc, true, find) { viewModel.scanDoc(lastDoc, true, find) {
launch { launch {
binding.refreshProgressBar.isAutoLoading = false binding.refreshProgressBar.isAutoLoading = false
@ -266,7 +267,7 @@ class ImportBookActivity : VMBaseActivity<ActivityImportBookBinding, ImportBookV
adapter.clearItems() adapter.clearItems()
val file = File(path) val file = File(path)
binding.refreshProgressBar.isAutoLoading = true binding.refreshProgressBar.isAutoLoading = true
launch(IO) { lifecycleScope.launch(IO) {
viewModel.scanFile(file, true, find) { viewModel.scanFile(file, true, find) {
launch { launch {
binding.refreshProgressBar.isAutoLoading = false binding.refreshProgressBar.isAutoLoading = false
@ -291,7 +292,7 @@ class ImportBookActivity : VMBaseActivity<ActivityImportBookBinding, ImportBookV
} }
private val find: (docItem: DocItem) -> Unit = { private val find: (docItem: DocItem) -> Unit = {
launch { lifecycleScope.launch {
adapter.addItem(it) adapter.addItem(it)
} }
} }

@ -13,6 +13,7 @@ import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.get import androidx.core.view.get
import androidx.core.view.isVisible import androidx.core.view.isVisible
import androidx.core.view.size import androidx.core.view.size
import androidx.lifecycle.lifecycleScope
import com.jaredrummler.android.colorpicker.ColorPickerDialogListener import com.jaredrummler.android.colorpicker.ColorPickerDialogListener
import io.legado.app.BuildConfig import io.legado.app.BuildConfig
import io.legado.app.R import io.legado.app.R
@ -108,7 +109,7 @@ class ReadBookActivity : ReadBookBaseActivity(),
TextActionMenu(this, this) TextActionMenu(this, this)
} }
override val scope: CoroutineScope get() = this override val scope: CoroutineScope get() = lifecycleScope
override val isInitFinish: Boolean get() = viewModel.isInitFinish override val isInitFinish: Boolean get() = viewModel.isInitFinish
override val isScroll: Boolean get() = binding.readView.isScroll override val isScroll: Boolean get() = binding.readView.isScroll
private val mHandler = Handler(Looper.getMainLooper()) private val mHandler = Handler(Looper.getMainLooper())
@ -591,7 +592,7 @@ class ReadBookActivity : ReadBookBaseActivity(),
resetPageOffset: Boolean, resetPageOffset: Boolean,
success: (() -> Unit)? success: (() -> Unit)?
) { ) {
launch { lifecycleScope.launch {
autoPageProgress = 0 autoPageProgress = 0
binding.readView.upContent(relativePosition, resetPageOffset) binding.readView.upContent(relativePosition, resetPageOffset)
binding.readMenu.setSeekPage(ReadBook.durPageIndex()) binding.readMenu.setSeekPage(ReadBook.durPageIndex())
@ -604,13 +605,13 @@ class ReadBookActivity : ReadBookBaseActivity(),
* 更新视图 * 更新视图
*/ */
override fun upView() { override fun upView() {
launch { lifecycleScope.launch {
binding.readMenu.upBookView() binding.readMenu.upBookView()
} }
} }
override fun upPageAnim() { override fun upPageAnim() {
launch { lifecycleScope.launch {
binding.readView.upPageAnim() binding.readView.upPageAnim()
} }
} }
@ -620,7 +621,7 @@ class ReadBookActivity : ReadBookBaseActivity(),
*/ */
override fun pageChanged() { override fun pageChanged() {
autoPageProgress = 0 autoPageProgress = 0
launch { lifecycleScope.launch {
binding.readMenu.setSeekPage(ReadBook.durPageIndex()) binding.readMenu.setSeekPage(ReadBook.durPageIndex())
} }
mHandler.postDelayed(backupRunnable, 600000) mHandler.postDelayed(backupRunnable, 600000)
@ -846,7 +847,7 @@ class ReadBookActivity : ReadBookBaseActivity(),
viewModel.searchContentQuery viewModel.searchContentQuery
) )
ReadBook.skipToPage(positions[0]) { ReadBook.skipToPage(positions[0]) {
launch { lifecycleScope.launch {
binding.readView.curPage.selectStartMoveIndex(0, positions[1], positions[2]) binding.readView.curPage.selectStartMoveIndex(0, positions[1], positions[2])
delay(20L) delay(20L)
when (positions[3]) { when (positions[3]) {
@ -936,7 +937,7 @@ class ReadBookActivity : ReadBookBaseActivity(),
} }
} }
observeEventSticky<Int>(EventBus.TTS_PROGRESS) { chapterStart -> observeEventSticky<Int>(EventBus.TTS_PROGRESS) { chapterStart ->
launch(IO) { lifecycleScope.launch(IO) {
if (BaseReadAloudService.isPlay()) { if (BaseReadAloudService.isPlay()) {
ReadBook.curTextChapter?.let { textChapter -> ReadBook.curTextChapter?.let { textChapter ->
val pageStart = chapterStart - ReadBook.durChapterPos val pageStart = chapterStart - ReadBook.durChapterPos

@ -2,6 +2,7 @@ package io.legado.app.ui.book.read
import android.app.Application import android.app.Application
import android.content.Intent import android.content.Intent
import androidx.lifecycle.viewModelScope
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.BaseViewModel import io.legado.app.base.BaseViewModel
import io.legado.app.data.appDb import io.legado.app.data.appDb
@ -104,7 +105,7 @@ class ReadBookViewModel(application: Application) : BaseViewModel(application) {
if (book.isLocalBook()) { if (book.isLocalBook()) {
loadChapterList(book, changeDruChapterIndex) loadChapterList(book, changeDruChapterIndex)
} else { } else {
ReadBook.webBook?.getBookInfo(this, book, canReName = false) ReadBook.webBook?.getBookInfo(viewModelScope, book, canReName = false)
?.onSuccess { ?.onSuccess {
loadChapterList(book, changeDruChapterIndex) loadChapterList(book, changeDruChapterIndex)
} }
@ -133,7 +134,7 @@ class ReadBookViewModel(application: Application) : BaseViewModel(application) {
ReadBook.upMsg("LoadTocError:${it.localizedMessage}") ReadBook.upMsg("LoadTocError:${it.localizedMessage}")
} }
} else { } else {
ReadBook.webBook?.getChapterList(this, book) ReadBook.webBook?.getChapterList(viewModelScope, book)
?.onSuccess(IO) { cList -> ?.onSuccess(IO) { cList ->
if (cList.isNotEmpty()) { if (cList.isNotEmpty()) {
if (changeDruChapterIndex == null) { if (changeDruChapterIndex == null) {

@ -11,6 +11,7 @@ import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentManager
import androidx.fragment.app.viewModels import androidx.fragment.app.viewModels
import androidx.lifecycle.LiveData import androidx.lifecycle.LiveData
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar import com.google.android.material.snackbar.Snackbar
@ -222,7 +223,7 @@ class TocRegexDialog : BaseDialogFragment(), Toolbar.OnMenuItemClickListener {
if (buttonView.isPressed) { if (buttonView.isPressed) {
getItem(holder.layoutPosition)?.let { getItem(holder.layoutPosition)?.let {
it.enable = isChecked it.enable = isChecked
launch(IO) { lifecycleScope.launch(IO) {
appDb.txtTocRuleDao.update(it) appDb.txtTocRuleDao.update(it)
} }
} }
@ -233,7 +234,7 @@ class TocRegexDialog : BaseDialogFragment(), Toolbar.OnMenuItemClickListener {
} }
ivDelete.setOnClickListener { ivDelete.setOnClickListener {
getItem(holder.layoutPosition)?.let { item -> getItem(holder.layoutPosition)?.let { item ->
launch(IO) { lifecycleScope.launch(IO) {
appDb.txtTocRuleDao.delete(item) appDb.txtTocRuleDao.delete(item)
} }
} }
@ -255,7 +256,7 @@ class TocRegexDialog : BaseDialogFragment(), Toolbar.OnMenuItemClickListener {
for ((index, item) in getItems().withIndex()) { for ((index, item) in getItems().withIndex()) {
item.serialNumber = index + 1 item.serialNumber = index + 1
} }
launch(IO) { lifecycleScope.launch(IO) {
appDb.txtTocRuleDao.update(*getItems().toTypedArray()) appDb.txtTocRuleDao.update(*getItems().toTypedArray())
} }
} }

@ -11,6 +11,7 @@ import android.widget.TextView
import androidx.activity.viewModels import androidx.activity.viewModels
import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.SearchView
import androidx.lifecycle.LiveData import androidx.lifecycle.LiveData
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import com.google.android.flexbox.FlexboxLayoutManager import com.google.android.flexbox.FlexboxLayoutManager
@ -192,7 +193,7 @@ class SearchActivity : VMBaseActivity<ActivityBookSearchBinding, SearchViewModel
} }
private fun initData() { private fun initData() {
launch { lifecycleScope.launch {
appDb.bookSourceDao.liveGroupEnabled().collect { appDb.bookSourceDao.liveGroupEnabled().collect {
groups.clear() groups.clear()
it.map { group -> it.map { group ->
@ -273,7 +274,7 @@ class SearchActivity : VMBaseActivity<ActivityBookSearchBinding, SearchViewModel
*/ */
private fun upHistory(key: String? = null) { private fun upHistory(key: String? = null) {
booksFlowJob?.cancel() booksFlowJob?.cancel()
booksFlowJob = launch { booksFlowJob = lifecycleScope.launch {
if (key.isNullOrBlank()) { if (key.isNullOrBlank()) {
binding.tvBookShow.gone() binding.tvBookShow.gone()
binding.rvBookshelfSearch.gone() binding.rvBookshelfSearch.gone()
@ -361,7 +362,7 @@ class SearchActivity : VMBaseActivity<ActivityBookSearchBinding, SearchViewModel
* 点击历史关键字 * 点击历史关键字
*/ */
override fun searchHistory(key: String) { override fun searchHistory(key: String) {
launch { lifecycleScope.launch {
when { when {
searchView.query.toString() == key -> { searchView.query.toString() == key -> {
searchView.setQuery(key, true) searchView.setQuery(key, true)

@ -4,6 +4,7 @@ import android.app.Application
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
import androidx.lifecycle.MutableLiveData import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import io.legado.app.base.BaseViewModel import io.legado.app.base.BaseViewModel
import io.legado.app.constant.PreferKey import io.legado.app.constant.PreferKey
import io.legado.app.data.appDb import io.legado.app.data.appDb
@ -17,7 +18,7 @@ import kotlinx.coroutines.isActive
class SearchViewModel(application: Application) : BaseViewModel(application), class SearchViewModel(application: Application) : BaseViewModel(application),
SearchBookModel.CallBack { SearchBookModel.CallBack {
val handler = Handler(Looper.getMainLooper()) val handler = Handler(Looper.getMainLooper())
private val searchBookModel = SearchBookModel(this, this) private val searchBookModel = SearchBookModel(viewModelScope, this)
var isSearchLiveData = MutableLiveData<Boolean>() var isSearchLiveData = MutableLiveData<Boolean>()
var searchBookLiveData = MutableLiveData<List<SearchBook>>() var searchBookLiveData = MutableLiveData<List<SearchBook>>()
var searchKey: String = "" var searchKey: String = ""
@ -64,7 +65,7 @@ class SearchViewModel(application: Application) : BaseViewModel(application),
override fun onSearchSuccess(searchBooks: ArrayList<SearchBook>) { override fun onSearchSuccess(searchBooks: ArrayList<SearchBook>) {
val precision = context.getPrefBoolean(PreferKey.precisionSearch) val precision = context.getPrefBoolean(PreferKey.precisionSearch)
appDb.searchBookDao.insert(*searchBooks.toTypedArray()) appDb.searchBookDao.insert(*searchBooks.toTypedArray())
mergeItems(this, searchBooks, precision) mergeItems(viewModelScope, searchBooks, precision)
} }
override fun onSearchFinish() { override fun onSearchFinish() {

@ -5,6 +5,7 @@ import android.content.Intent
import android.os.Bundle import android.os.Bundle
import androidx.activity.viewModels import androidx.activity.viewModels
import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.SearchView
import androidx.lifecycle.lifecycleScope
import com.github.liuyueyi.quick.transfer.ChineseUtils import com.github.liuyueyi.quick.transfer.ChineseUtils
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.VMBaseActivity import io.legado.app.base.VMBaseActivity
@ -115,7 +116,7 @@ class SearchContentActivity :
} }
private fun initCacheFileNames(book: Book) { private fun initCacheFileNames(book: Book) {
launch(Dispatchers.IO) { lifecycleScope.launch(Dispatchers.IO) {
adapter.cacheFileNames.addAll(BookHelp.getChapterFiles(book)) adapter.cacheFileNames.addAll(BookHelp.getChapterFiles(book))
withContext(Dispatchers.Main) { withContext(Dispatchers.Main) {
adapter.notifyItemRangeChanged(0, adapter.itemCount, true) adapter.notifyItemRangeChanged(0, adapter.itemCount, true)
@ -144,7 +145,7 @@ class SearchContentActivity :
searchResultCounts = 0 searchResultCounts = 0
viewModel.lastQuery = newText viewModel.lastQuery = newText
var searchResults = listOf<SearchResult>() var searchResults = listOf<SearchResult>()
launch(Dispatchers.Main) { lifecycleScope.launch(Dispatchers.Main) {
appDb.bookChapterDao.getChapterList(viewModel.bookUrl).map { chapter -> appDb.bookChapterDao.getChapterList(viewModel.bookUrl).map { chapter ->
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
if (isLocalBook if (isLocalBook

@ -5,6 +5,7 @@ import android.view.Menu
import android.view.MenuItem import android.view.MenuItem
import androidx.activity.viewModels import androidx.activity.viewModels
import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.SearchView
import androidx.lifecycle.lifecycleScope
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.VMBaseActivity import io.legado.app.base.VMBaseActivity
import io.legado.app.databinding.ActivitySourceDebugBinding import io.legado.app.databinding.ActivitySourceDebugBinding
@ -36,7 +37,7 @@ class BookSourceDebugActivity : VMBaseActivity<ActivitySourceDebugBinding, BookS
initRecyclerView() initRecyclerView()
initSearchView() initSearchView()
viewModel.observe { state, msg -> viewModel.observe { state, msg ->
launch { lifecycleScope.launch {
adapter.addItem(msg) adapter.addItem(msg)
if (state == -1 || state == 1000) { if (state == -1 || state == 1000) {
binding.rotateLoading.hide() binding.rotateLoading.hide()

@ -10,6 +10,7 @@ import androidx.activity.viewModels
import androidx.appcompat.widget.PopupMenu import androidx.appcompat.widget.PopupMenu
import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.SearchView
import androidx.documentfile.provider.DocumentFile import androidx.documentfile.provider.DocumentFile
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.ItemTouchHelper
import com.google.android.material.snackbar.Snackbar import com.google.android.material.snackbar.Snackbar
import io.legado.app.R import io.legado.app.R
@ -203,7 +204,7 @@ class BookSourceActivity : VMBaseActivity<ActivityBookSourceBinding, BookSourceV
private fun upBookSource(searchKey: String? = null) { private fun upBookSource(searchKey: String? = null) {
sourceFlowJob?.cancel() sourceFlowJob?.cancel()
sourceFlowJob = launch { sourceFlowJob = lifecycleScope.launch {
when { when {
searchKey.isNullOrEmpty() -> { searchKey.isNullOrEmpty() -> {
appDb.bookSourceDao.liveDataAll() appDb.bookSourceDao.liveDataAll()
@ -275,7 +276,7 @@ class BookSourceActivity : VMBaseActivity<ActivityBookSourceBinding, BookSourceV
} }
private fun initLiveDataGroup() { private fun initLiveDataGroup() {
launch { lifecycleScope.launch {
appDb.bookSourceDao.liveGroup() appDb.bookSourceDao.liveGroup()
.collect { .collect {
groups.clear() groups.clear()

@ -9,6 +9,7 @@ import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import androidx.appcompat.widget.Toolbar import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.activityViewModels import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.BaseDialogFragment import io.legado.app.base.BaseDialogFragment
@ -66,7 +67,7 @@ class GroupManageDialog : BaseDialogFragment(), Toolbar.OnMenuItemClickListener
} }
private fun initData() { private fun initData() {
launch { lifecycleScope.launch {
appDb.bookSourceDao.liveGroup().collect { appDb.bookSourceDao.liveGroup().collect {
val groups = linkedSetOf<String>() val groups = linkedSetOf<String>()
it.map { group -> it.map { group ->

@ -5,6 +5,7 @@ import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.view.View import android.view.View
import androidx.fragment.app.activityViewModels import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.VMBaseFragment import io.legado.app.base.VMBaseFragment
@ -50,7 +51,7 @@ class BookmarkFragment : VMBaseFragment<TocViewModel>(R.layout.fragment_bookmark
override fun upBookmark(searchKey: String?) { override fun upBookmark(searchKey: String?) {
val book = viewModel.bookData.value ?: return val book = viewModel.bookData.value ?: return
bookmarkFlowJob?.cancel() bookmarkFlowJob?.cancel()
bookmarkFlowJob = launch { bookmarkFlowJob = lifecycleScope.launch {
when { when {
searchKey.isNullOrBlank() -> appDb.bookmarkDao.observeByBook(book.name, book.author) searchKey.isNullOrBlank() -> appDb.bookmarkDao.observeByBook(book.name, book.author)
else -> appDb.bookmarkDao.liveDataSearch(book.name, book.author, searchKey) else -> appDb.bookmarkDao.liveDataSearch(book.name, book.author, searchKey)

@ -6,6 +6,7 @@ import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.view.View import android.view.View
import androidx.fragment.app.activityViewModels import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.VMBaseFragment import io.legado.app.base.VMBaseFragment
import io.legado.app.constant.EventBus import io.legado.app.constant.EventBus
@ -77,7 +78,7 @@ class ChapterListFragment : VMBaseFragment<TocViewModel>(R.layout.fragment_chapt
@SuppressLint("SetTextI18n") @SuppressLint("SetTextI18n")
private fun initBook(book: Book) { private fun initBook(book: Book) {
launch { lifecycleScope.launch {
upChapterList(null) upChapterList(null)
durChapterIndex = book.durChapterIndex durChapterIndex = book.durChapterIndex
binding.tvCurrentChapterInfo.text = binding.tvCurrentChapterInfo.text =
@ -87,7 +88,7 @@ class ChapterListFragment : VMBaseFragment<TocViewModel>(R.layout.fragment_chapt
} }
private fun initCacheFileNames(book: Book) { private fun initCacheFileNames(book: Book) {
launch(IO) { lifecycleScope.launch(IO) {
adapter.cacheFileNames.addAll(BookHelp.getChapterFiles(book)) adapter.cacheFileNames.addAll(BookHelp.getChapterFiles(book))
withContext(Main) { withContext(Main) {
adapter.notifyItemRangeChanged(0, adapter.itemCount, true) adapter.notifyItemRangeChanged(0, adapter.itemCount, true)
@ -108,7 +109,7 @@ class ChapterListFragment : VMBaseFragment<TocViewModel>(R.layout.fragment_chapt
override fun upChapterList(searchKey: String?) { override fun upChapterList(searchKey: String?) {
tocFlowJob?.cancel() tocFlowJob?.cancel()
tocFlowJob = launch { tocFlowJob = lifecycleScope.launch {
when { when {
searchKey.isNullOrBlank() -> appDb.bookChapterDao.observeByBook(viewModel.bookUrl) searchKey.isNullOrBlank() -> appDb.bookChapterDao.observeByBook(viewModel.bookUrl)
else -> appDb.bookChapterDao.liveDataSearch(viewModel.bookUrl, searchKey) else -> appDb.bookChapterDao.liveDataSearch(viewModel.bookUrl, searchKey)

@ -10,7 +10,7 @@ import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.lifecycle.LiveData import androidx.lifecycle.lifecycleScope
import com.google.android.material.tabs.TabLayout import com.google.android.material.tabs.TabLayout
import io.legado.app.R import io.legado.app.R
import io.legado.app.constant.AppConst import io.legado.app.constant.AppConst
@ -28,6 +28,8 @@ import io.legado.app.utils.getPrefInt
import io.legado.app.utils.putPrefInt import io.legado.app.utils.putPrefInt
import io.legado.app.utils.toastOnUi import io.legado.app.utils.toastOnUi
import io.legado.app.utils.viewbindingdelegate.viewBinding import io.legado.app.utils.viewbindingdelegate.viewBinding
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
/** /**
* 书架界面 * 书架界面
@ -39,7 +41,6 @@ class BookshelfFragment1 : BaseBookshelfFragment(R.layout.fragment_bookshelf),
private val binding by viewBinding(FragmentBookshelfBinding::bind) private val binding by viewBinding(FragmentBookshelfBinding::bind)
private lateinit var adapter: FragmentStatePagerAdapter private lateinit var adapter: FragmentStatePagerAdapter
private lateinit var tabLayout: TabLayout private lateinit var tabLayout: TabLayout
private var bookGroupLiveData: LiveData<List<BookGroup>>? = null
private val bookGroups = mutableListOf<BookGroup>() private val bookGroups = mutableListOf<BookGroup>()
private val fragmentMap = hashMapOf<Long, BooksFragment>() private val fragmentMap = hashMapOf<Long, BooksFragment>()
@ -77,9 +78,8 @@ class BookshelfFragment1 : BaseBookshelfFragment(R.layout.fragment_bookshelf),
} }
private fun initBookGroupData() { private fun initBookGroupData() {
bookGroupLiveData?.removeObservers(viewLifecycleOwner) lifecycleScope.launch {
bookGroupLiveData = appDb.bookGroupDao.liveDataShow().apply { appDb.bookGroupDao.liveDataShow().collect {
observe(viewLifecycleOwner) {
viewModel.checkGroup(it) viewModel.checkGroup(it)
upGroup(it) upGroup(it)
} }

@ -4,6 +4,7 @@ import android.os.Bundle
import android.view.View import android.view.View
import androidx.core.view.isGone import androidx.core.view.isGone
import androidx.fragment.app.activityViewModels import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
@ -104,7 +105,7 @@ class BooksFragment : BaseFragment(R.layout.fragment_books),
private fun upRecyclerData() { private fun upRecyclerData() {
booksFlowJob?.cancel() booksFlowJob?.cancel()
booksFlowJob = launch { booksFlowJob = lifecycleScope.launch {
when (groupId) { when (groupId) {
AppConst.bookGroupAllId -> appDb.bookDao.observeAll() AppConst.bookGroupAllId -> appDb.bookDao.observeAll()
AppConst.bookGroupLocalId -> appDb.bookDao.observeLocal() AppConst.bookGroupLocalId -> appDb.bookDao.observeLocal()

@ -6,6 +6,7 @@ import android.view.View
import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.SearchView
import androidx.core.view.isGone import androidx.core.view.isGone
import androidx.lifecycle.LiveData import androidx.lifecycle.LiveData
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
@ -121,9 +122,8 @@ class BookshelfFragment2 : BaseBookshelfFragment(R.layout.fragment_bookshelf1),
} }
private fun initGroupData() { private fun initGroupData() {
bookGroupLiveData?.removeObservers(this) lifecycleScope.launch {
bookGroupLiveData = appDb.bookGroupDao.liveDataShow().apply { appDb.bookGroupDao.liveDataShow().collect {
observe(viewLifecycleOwner) {
if (it != bookGroups) { if (it != bookGroups) {
bookGroups = it bookGroups = it
booksAdapter.notifyDataSetChanged() booksAdapter.notifyDataSetChanged()
@ -134,7 +134,7 @@ class BookshelfFragment2 : BaseBookshelfFragment(R.layout.fragment_bookshelf1),
private fun initBooksData() { private fun initBooksData() {
booksFlowJob?.cancel() booksFlowJob?.cancel()
booksFlowJob = launch { booksFlowJob = lifecycleScope.launch {
when (groupId) { when (groupId) {
AppConst.bookGroupAllId -> appDb.bookDao.observeAll() AppConst.bookGroupAllId -> appDb.bookDao.observeAll()
AppConst.bookGroupLocalId -> appDb.bookDao.observeLocal() AppConst.bookGroupLocalId -> appDb.bookDao.observeLocal()

@ -8,6 +8,7 @@ import android.view.View
import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.SearchView
import androidx.core.view.isGone import androidx.core.view.isGone
import androidx.fragment.app.viewModels import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
@ -87,7 +88,7 @@ class ExploreFragment : VMBaseFragment<ExploreViewModel>(R.layout.fragment_explo
ATH.applyEdgeEffectColor(binding.rvFind) ATH.applyEdgeEffectColor(binding.rvFind)
linearLayoutManager = LinearLayoutManager(context) linearLayoutManager = LinearLayoutManager(context)
binding.rvFind.layoutManager = linearLayoutManager binding.rvFind.layoutManager = linearLayoutManager
adapter = ExploreAdapter(requireContext(), this, this) adapter = ExploreAdapter(requireContext(), lifecycleScope, this)
binding.rvFind.adapter = adapter binding.rvFind.adapter = adapter
adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() { adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
@ -101,7 +102,7 @@ class ExploreFragment : VMBaseFragment<ExploreViewModel>(R.layout.fragment_explo
} }
private fun initGroupData() { private fun initGroupData() {
launch { lifecycleScope.launch {
appDb.bookSourceDao.liveExploreGroup() appDb.bookSourceDao.liveExploreGroup()
.collect { .collect {
groups.clear() groups.clear()
@ -115,7 +116,7 @@ class ExploreFragment : VMBaseFragment<ExploreViewModel>(R.layout.fragment_explo
private fun upExploreData(searchKey: String? = null) { private fun upExploreData(searchKey: String? = null) {
exploreFlowJob?.cancel() exploreFlowJob?.cancel()
exploreFlowJob = launch { exploreFlowJob = lifecycleScope.launch {
val exploreFlow = when { val exploreFlow = when {
searchKey.isNullOrBlank() -> { searchKey.isNullOrBlank() -> {
appDb.bookSourceDao.liveExplore() appDb.bookSourceDao.liveExplore()

@ -7,6 +7,7 @@ import android.view.SubMenu
import android.view.View import android.view.View
import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.SearchView
import androidx.fragment.app.viewModels import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.VMBaseFragment import io.legado.app.base.VMBaseFragment
import io.legado.app.constant.AppPattern import io.legado.app.constant.AppPattern
@ -120,7 +121,7 @@ class RssFragment : VMBaseFragment<RssSourceViewModel>(R.layout.fragment_rss),
} }
private fun initGroupData() { private fun initGroupData() {
launch { lifecycleScope.launch {
appDb.rssSourceDao.liveGroup().collect { appDb.rssSourceDao.liveGroup().collect {
groups.clear() groups.clear()
it.map { group -> it.map { group ->
@ -133,7 +134,7 @@ class RssFragment : VMBaseFragment<RssSourceViewModel>(R.layout.fragment_rss),
private fun upRssFlowJob(searchKey: String? = null) { private fun upRssFlowJob(searchKey: String? = null) {
rssFlowJob?.cancel() rssFlowJob?.cancel()
rssFlowJob = launch { rssFlowJob = lifecycleScope.launch {
when { when {
searchKey.isNullOrEmpty() -> appDb.rssSourceDao.liveEnabled() searchKey.isNullOrEmpty() -> appDb.rssSourceDao.liveEnabled()
searchKey.startsWith("group:") -> { searchKey.startsWith("group:") -> {

@ -5,6 +5,7 @@ import android.os.Bundle
import android.view.View import android.view.View
import androidx.fragment.app.activityViewModels import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
@ -96,7 +97,7 @@ class RssArticlesFragment : VMBaseFragment<RssArticlesViewModel>(R.layout.fragme
private fun initData() { private fun initData() {
val rssUrl = activityViewModel.url ?: return val rssUrl = activityViewModel.url ?: return
articlesFlowJob?.cancel() articlesFlowJob?.cancel()
articlesFlowJob = launch { articlesFlowJob = lifecycleScope.launch {
appDb.rssArticleDao.liveByOriginSort(rssUrl, viewModel.sortName).collect { appDb.rssArticleDao.liveByOriginSort(rssUrl, viewModel.sortName).collect {
adapter.setItems(it) adapter.setItems(it)
} }

@ -3,6 +3,7 @@ package io.legado.app.ui.rss.article
import android.app.Application import android.app.Application
import android.os.Bundle import android.os.Bundle
import androidx.lifecycle.MutableLiveData import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import io.legado.app.base.BaseViewModel import io.legado.app.base.BaseViewModel
import io.legado.app.data.appDb import io.legado.app.data.appDb
import io.legado.app.data.entities.RssArticle import io.legado.app.data.entities.RssArticle
@ -30,7 +31,7 @@ class RssArticlesViewModel(application: Application) : BaseViewModel(application
fun loadContent(rssSource: RssSource) { fun loadContent(rssSource: RssSource) {
isLoading = true isLoading = true
page = 1 page = 1
Rss.getArticles(this, sortName, sortUrl, rssSource, page) Rss.getArticles(viewModelScope, sortName, sortUrl, rssSource, page)
.onSuccess(Dispatchers.IO) { .onSuccess(Dispatchers.IO) {
nextPageUrl = it.nextPageUrl nextPageUrl = it.nextPageUrl
it.articles.let { list -> it.articles.let { list ->
@ -60,7 +61,7 @@ class RssArticlesViewModel(application: Application) : BaseViewModel(application
page++ page++
val pageUrl = nextPageUrl val pageUrl = nextPageUrl
if (!pageUrl.isNullOrEmpty()) { if (!pageUrl.isNullOrEmpty()) {
Rss.getArticles(this, sortName, pageUrl, rssSource, page) Rss.getArticles(viewModelScope, sortName, pageUrl, rssSource, page)
.onSuccess(Dispatchers.IO) { .onSuccess(Dispatchers.IO) {
nextPageUrl = it.nextPageUrl nextPageUrl = it.nextPageUrl
loadMoreSuccess(it.articles) loadMoreSuccess(it.articles)

@ -1,6 +1,7 @@
package io.legado.app.ui.rss.favorites package io.legado.app.ui.rss.favorites
import android.os.Bundle import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import io.legado.app.base.BaseActivity import io.legado.app.base.BaseActivity
import io.legado.app.data.appDb import io.legado.app.data.appDb
@ -35,7 +36,7 @@ class RssFavoritesActivity : BaseActivity<ActivityRssFavoritesBinding>(),
} }
private fun initData() { private fun initData() {
launch { lifecycleScope.launch {
appDb.rssStarDao.liveAll().collect { appDb.rssStarDao.liveAll().collect {
adapter.setItems(it) adapter.setItems(it)
} }

@ -12,6 +12,7 @@ import android.view.*
import android.webkit.* import android.webkit.*
import androidx.activity.viewModels import androidx.activity.viewModels
import androidx.core.view.size import androidx.core.view.size
import androidx.lifecycle.lifecycleScope
import androidx.webkit.WebSettingsCompat import androidx.webkit.WebSettingsCompat
import androidx.webkit.WebViewFeature import androidx.webkit.WebViewFeature
import io.legado.app.R import io.legado.app.R
@ -231,7 +232,7 @@ class ReadRssActivity : VMBaseActivity<ActivityRssReadBinding, ReadRssViewModel>
} }
override fun upTtsMenu(isPlaying: Boolean) { override fun upTtsMenu(isPlaying: Boolean) {
launch { lifecycleScope.launch {
if (isPlaying) { if (isPlaying) {
ttsMenuItem?.setIcon(R.drawable.ic_stop_black_24dp) ttsMenuItem?.setIcon(R.drawable.ic_stop_black_24dp)
ttsMenuItem?.setTitle(R.string.aloud_stop) ttsMenuItem?.setTitle(R.string.aloud_stop)

@ -9,6 +9,7 @@ import android.util.Base64
import android.webkit.URLUtil import android.webkit.URLUtil
import androidx.documentfile.provider.DocumentFile import androidx.documentfile.provider.DocumentFile
import androidx.lifecycle.MutableLiveData import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.BaseViewModel import io.legado.app.base.BaseViewModel
import io.legado.app.constant.AppConst import io.legado.app.constant.AppConst
@ -25,7 +26,6 @@ import io.legado.app.utils.FileUtils
import io.legado.app.utils.isContentScheme import io.legado.app.utils.isContentScheme
import io.legado.app.utils.writeBytes import io.legado.app.utils.writeBytes
import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch
import java.io.File import java.io.File
import java.util.* import java.util.*
@ -95,7 +95,7 @@ class ReadRssViewModel(application: Application) : BaseViewModel(application),
private fun loadContent(rssArticle: RssArticle, ruleContent: String) { private fun loadContent(rssArticle: RssArticle, ruleContent: String) {
rssSource?.let { source -> rssSource?.let { source ->
Rss.getContent(this, rssArticle, ruleContent, source) Rss.getContent(viewModelScope, rssArticle, ruleContent, source)
.onSuccess(IO) { body -> .onSuccess(IO) { body ->
rssArticle.description = body rssArticle.description = body
appDb.rssArticleDao.insert(rssArticle) appDb.rssArticleDao.insert(rssArticle)
@ -189,11 +189,9 @@ class ReadRssViewModel(application: Application) : BaseViewModel(application),
ttsInitFinish = true ttsInitFinish = true
play() play()
} else { } else {
launch {
toastOnUi(R.string.tts_init_failed) toastOnUi(R.string.tts_init_failed)
} }
} }
}
@Synchronized @Synchronized
private fun play() { private fun play() {

@ -5,6 +5,7 @@ import android.view.Menu
import android.view.MenuItem import android.view.MenuItem
import android.widget.SearchView import android.widget.SearchView
import androidx.activity.viewModels import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.VMBaseActivity import io.legado.app.base.VMBaseActivity
import io.legado.app.databinding.ActivitySourceDebugBinding import io.legado.app.databinding.ActivitySourceDebugBinding
@ -29,7 +30,7 @@ class RssSourceDebugActivity : VMBaseActivity<ActivitySourceDebugBinding, RssSou
initRecyclerView() initRecyclerView()
initSearchView() initSearchView()
viewModel.observe { state, msg -> viewModel.observe { state, msg ->
launch { lifecycleScope.launch {
adapter.addItem(msg) adapter.addItem(msg)
if (state == -1 || state == 1000) { if (state == -1 || state == 1000) {
binding.rotateLoading.hide() binding.rotateLoading.hide()

@ -1,6 +1,7 @@
package io.legado.app.ui.rss.source.debug package io.legado.app.ui.rss.source.debug
import android.app.Application import android.app.Application
import androidx.lifecycle.viewModelScope
import io.legado.app.base.BaseViewModel import io.legado.app.base.BaseViewModel
import io.legado.app.data.appDb import io.legado.app.data.appDb
import io.legado.app.data.entities.RssSource import io.legado.app.data.entities.RssSource
@ -31,7 +32,7 @@ class RssSourceDebugModel(application: Application) : BaseViewModel(application)
rssSource?.let { rssSource?.let {
start?.invoke() start?.invoke()
Debug.callback = this Debug.callback = this
Debug.startDebug(this, it) Debug.startDebug(viewModelScope, it)
} ?: error?.invoke() } ?: error?.invoke()
} }

@ -9,6 +9,7 @@ import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import androidx.appcompat.widget.Toolbar import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.activityViewModels import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.BaseDialogFragment import io.legado.app.base.BaseDialogFragment
@ -68,7 +69,7 @@ class GroupManageDialog : BaseDialogFragment(), Toolbar.OnMenuItemClickListener
} }
private fun initData() { private fun initData() {
launch { lifecycleScope.launch {
appDb.rssSourceDao.liveGroup().collect { appDb.rssSourceDao.liveGroup().collect {
val groups = linkedSetOf<String>() val groups = linkedSetOf<String>()
it.map { group -> it.map { group ->

@ -10,6 +10,7 @@ import androidx.activity.viewModels
import androidx.appcompat.widget.PopupMenu import androidx.appcompat.widget.PopupMenu
import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.SearchView
import androidx.documentfile.provider.DocumentFile import androidx.documentfile.provider.DocumentFile
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.ItemTouchHelper
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.VMBaseActivity import io.legado.app.base.VMBaseActivity
@ -178,7 +179,7 @@ class RssSourceActivity : VMBaseActivity<ActivityRssSourceBinding, RssSourceView
} }
private fun initGroupFlow() { private fun initGroupFlow() {
launch { lifecycleScope.launch {
appDb.rssSourceDao.liveGroup().collect { appDb.rssSourceDao.liveGroup().collect {
groups.clear() groups.clear()
it.map { group -> it.map { group ->
@ -230,7 +231,7 @@ class RssSourceActivity : VMBaseActivity<ActivityRssSourceBinding, RssSourceView
private fun upSourceFlow(searchKey: String? = null) { private fun upSourceFlow(searchKey: String? = null) {
sourceFlowJob?.cancel() sourceFlowJob?.cancel()
sourceFlowJob = launch { sourceFlowJob = lifecycleScope.launch {
when { when {
searchKey.isNullOrBlank() -> { searchKey.isNullOrBlank() -> {
appDb.rssSourceDao.liveAll() appDb.rssSourceDao.liveAll()

@ -5,6 +5,7 @@ import android.view.Menu
import android.view.MenuItem import android.view.MenuItem
import androidx.core.view.isGone import androidx.core.view.isGone
import androidx.lifecycle.LiveData import androidx.lifecycle.LiveData
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.ItemTouchHelper
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.BaseActivity import io.legado.app.base.BaseActivity
@ -100,7 +101,7 @@ class RuleSubActivity : BaseActivity<ActivityRuleSubBinding>(),
} }
customView { alertBinding.root } customView { alertBinding.root }
okButton { okButton {
launch { lifecycleScope.launch {
ruleSub.type = alertBinding.spType.selectedItemPosition ruleSub.type = alertBinding.spType.selectedItemPosition
ruleSub.name = alertBinding.etName.text?.toString() ?: "" ruleSub.name = alertBinding.etName.text?.toString() ?: ""
ruleSub.url = alertBinding.etUrl.text?.toString() ?: "" ruleSub.url = alertBinding.etUrl.text?.toString() ?: ""
@ -121,19 +122,19 @@ class RuleSubActivity : BaseActivity<ActivityRuleSubBinding>(),
} }
override fun delSubscription(ruleSub: RuleSub) { override fun delSubscription(ruleSub: RuleSub) {
launch(IO) { lifecycleScope.launch(IO) {
appDb.ruleSubDao.delete(ruleSub) appDb.ruleSubDao.delete(ruleSub)
} }
} }
override fun updateSourceSub(vararg ruleSub: RuleSub) { override fun updateSourceSub(vararg ruleSub: RuleSub) {
launch(IO) { lifecycleScope.launch(IO) {
appDb.ruleSubDao.update(*ruleSub) appDb.ruleSubDao.update(*ruleSub)
} }
} }
override fun upOrder() { override fun upOrder() {
launch(IO) { lifecycleScope.launch(IO) {
val sourceSubs = appDb.ruleSubDao.all val sourceSubs = appDb.ruleSubDao.all
for ((index: Int, ruleSub: RuleSub) in sourceSubs.withIndex()) { for ((index: Int, ruleSub: RuleSub) in sourceSubs.withIndex()) {
ruleSub.customOrder = index + 1 ruleSub.customOrder = index + 1

@ -5,6 +5,7 @@ import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentManager
import androidx.lifecycle.lifecycleScope
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.BaseDialogFragment import io.legado.app.base.BaseDialogFragment
import io.legado.app.databinding.DialogTextViewBinding import io.legado.app.databinding.DialogTextViewBinding
@ -79,7 +80,7 @@ class TextDialog : BaseDialogFragment() {
} }
if (time > 0) { if (time > 0) {
binding.badgeView.setBadgeCount((time / 1000).toInt()) binding.badgeView.setBadgeCount((time / 1000).toInt())
launch { lifecycleScope.launch {
while (time > 0) { while (time > 0) {
delay(1000) delay(1000)
time -= 1000 time -= 1000

@ -9,6 +9,7 @@ import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import androidx.appcompat.widget.Toolbar import androidx.appcompat.widget.Toolbar
import androidx.documentfile.provider.DocumentFile import androidx.documentfile.provider.DocumentFile
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.BaseDialogFragment import io.legado.app.base.BaseDialogFragment
@ -126,7 +127,7 @@ class FontSelectDialog : BaseDialogFragment(),
} }
private fun openFolder() { private fun openFolder() {
launch(Main) { lifecycleScope.launch(Main) {
val defaultPath = "SD${File.separator}Fonts" val defaultPath = "SD${File.separator}Fonts"
selectFontDir.launch( selectFontDir.launch(
FilePickerParam( FilePickerParam(

Loading…
Cancel
Save