0

I'd like to ask about scope cancelation. Is it 100% synchronous?

 someOtherPlace {
    someUserScope.launch {
        val userFlow: Flow<User?> = userDao.user()
        userFlow
         .collect {
              // can 'it' be null here?
          }
    }
 }
 
 fun logout() {
     allUserCoroutineScopes.forEach { it.cancel() }
     userDao.deleteUser() // btw this is blocking
 }

lets assume someUserScope is in the allUserCoroutineScopes list, and I'll only delete user after running the cancelation forEach

Is there a way the flow at the top will emit null? Should never happen, right? Is it safe to !! there? (I'm looking at sources but its non obvious to me)

Rx checks for disposal so it never emits once disposed. Is this the case with coroutines Flow?

urSus
  • 12,492
  • 12
  • 69
  • 89
  • 1
    `Is it safe to !! there?` Yes, the collection will be stopped but a safer decision will be to just ignore the `null` values if you don't want to process them -> `it ?: return@collect` – Arpit Shukla Nov 17 '21 at 04:32
  • What about this? https://kotlinlang.org/docs/flow.html#flow-cancellation-checks It feels it might keep emitting, for whatever reason – urSus Nov 17 '21 at 04:37
  • What are you pointing to in the documentation? – Arpit Shukla Nov 17 '21 at 04:38
  • Im pointing to the cancelatiom checks section, where in the snippet, emit 4 happens, which is not obvious to me why, if it was canceled on 3rd – urSus Nov 17 '21 at 04:42
  • `the flow builder performs additional ensureActive checks for cancellation on each emitted value`. It prints "Emitting 3", then emits 3 (scope is active so emission succeeds). Next when `i=4` it first prints "Emitting 4" and then calls emit which checks whether scope is active or not. Since it isn't active it throws the exception. – Arpit Shukla Nov 17 '21 at 04:53

0 Answers0