@@ -10,6 +10,7 @@ import androidx.navigation.NavController
1010import kotlinx.coroutines.CoroutineDispatcher
1111import kotlinx.coroutines.CoroutineScope
1212import kotlinx.coroutines.Dispatchers
13+ import kotlinx.coroutines.ensureActive
1314import kotlinx.coroutines.launch
1415import kotlinx.coroutines.withContext
1516import mozilla.appservices.places.BookmarkRoot
@@ -72,10 +73,11 @@ internal class BookmarksMiddleware(
7273 private val saveBookmarkSortOrder : suspend (BookmarksListSortOrder ) -> Unit ,
7374 private val lastSavedFolderCache : LastSavedFolderCache ,
7475 private val reportResultGlobally : (BookmarksGlobalResultReport ) -> Unit ,
76+ private val lifecycleScope : CoroutineScope ,
7577 private val ioDispatcher : CoroutineDispatcher = Dispatchers .IO ,
7678) : Middleware<BookmarksState, BookmarksAction> {
7779
78- private val scope = CoroutineScope (ioDispatcher)
80+ private val scope = CoroutineScope (lifecycleScope.coroutineContext + ioDispatcher)
7981
8082 @Suppress(" LongMethod" , " CognitiveComplexMethod" , " CyclomaticComplexMethod" )
8183 override fun invoke (
@@ -96,7 +98,7 @@ internal class BookmarksMiddleware(
9698 }
9799
98100 when (action) {
99- Init -> store.tryDispatchLoadFor(BookmarkRoot . Mobile .id )
101+ Init -> store.tryDispatchLoadFor(store.state.currentFolder.guid )
100102 is InitEdit -> scope.launch {
101103 Result .runCatching {
102104 val bookmarkNode = bookmarksStorage.getBookmark(action.guid).getOrNull()
@@ -278,6 +280,10 @@ internal class BookmarksMiddleware(
278280 }
279281 // list screen cases
280282 preReductionState.selectedItems.isNotEmpty() -> { /* noop */ }
283+ // User is clicking back before we've loaded anything
284+ preReductionState.currentFolder.guid.isEmpty() -> {
285+ exitBookmarks()
286+ }
281287 preReductionState.currentFolder.guid != BookmarkRoot .Mobile .id -> {
282288 scope.launch {
283289 val parentFolderGuid = withContext(ioDispatcher) {
@@ -516,6 +522,8 @@ internal class BookmarksMiddleware(
516522 private fun Store <BookmarksState , BookmarksAction >.tryDispatchLoadFor (guid : String ) =
517523 scope.launch {
518524 bookmarksStorage.getTree(guid).getOrNull()?.let { rootNode ->
525+ ensureActive()
526+
519527 val folder = BookmarkItem .Folder (
520528 guid = guid,
521529 title = resolveFolderTitle(rootNode),
0 commit comments