Propagating errors from query flow to outer catch block

I admit…the design have issues but looking for a quick solution for now. I have this code

try {
val query = query goes here
val queryFlow =
                query
                    .queryChangeFlow()
                    .map { queryChange ->
                        val err = queryChange.error
                        if (err != null) {
                            throw err
                        }

                        val data =
                            queryChange.results?.allResults()?.mapNotNull { result ->
                                val cblDocument = result.getDictionary(0)
                                val doc = cblDocument?.toDataClass<UserData>()
                                doc
                            } ?: emptyList()
                        data
                    }.asLiveData()
            return queryFlow.asFlow()
        } catch (e: Exception) {
            Log.e("MLG", e)
            throw e
        }

Now toDataClass might be unable to parse the document, thus crashing the app. I want to catch it instead
and propogate it to the outer catch block. If toDataClass is okay, the app works well.

I am struggling to pass the error from inside query flow to the outside while keeping the return and implementaiton of the method as is due to lack of time.

Any ideas please?

Yes.

The flow you have now, maps QueryChanges into either immediate failures (when queryChange contains an error, OR when toDataClass fails), or to lists of UserData objects.

Instead, you need to map QueryChanges into Options that contains either a list of UserData objects (on success), or an exception (on failure)

… and I cannot resist a couple other comments:

  • Why are you converting the flow to live data and then the live data back to a flow? That seems excessive.
  • The try-catch block that you have wrapping the creation of the flow is a NOOP. It will catch exceptions thrown by the asLiveData and the asFlow methods, only
  • It seems odd, to me, to have a flow of lists of UserData. Perhaps you should consider flatMapping?