0

I have Coroutines code which is using a callbackFlow like this:

fun getUniqueEventAsFlow(receiverId: String): Flow<Any> = callbackFlow {
    RxEventBus().register(
        receiverId,
        FirstUniqueEvent::class.java,
        false
    ) { amEvent ->
        offer(amEvent)
    }
    // Suspend until either onCompleted or external cancellation are invoked
    awaitClose {
        unsubscribeFromEventBus(receiverId)
        cancel()
    }
}.flowOn(Dispatchers.Default)
    .catch { throwable ->
        reportError(throwable as Exception)
    }

What I'd like to do is wrap the following so that it can be called automatically, since I have many similar functions in the code:

        // Suspend until either onCompleted or external cancellation are invoked
        awaitClose {
            unsubscribeFromEventBus(receiverId)
            cancel()
        }
    }.flowOn(Dispatchers.Default)
        .catch { throwable ->
            reportError(throwable as Exception)
        }

I would like to wrap the awaitClose & flowOn once, and not have to write it for every callbackFlow. Do you know which Kotlin higher order construct I can use to achieve this?

Thank you, Igor

IgorGanapolsky
  • 26,189
  • 23
  • 116
  • 147

1 Answers1

0

Here is the solution for wrapping awaitClose and handleErrors:

/**
 * Utility function which suspends a coroutine until it is completed or closed.
 * Unsubscribes from Rx Bus event and ensures that the scope is cancelled upon completion.
 */
suspend fun finalizeFlow(scope: ProducerScope<Any>, receiverId: String) {
    scope.awaitClose {
        unsubscribeFromEventBus(receiverId)
        scope.cancel()
    }

    scope.invokeOnClose {
        Logger.debug(
            javaClass.canonicalName,
            "Closed Flow channel for receiverId $receiverId"
        )
    }
}

 /**
  * Extension function which does error handling on [Flow].
  */
 fun <T> Flow<T>.handleErrors(): Flow<T> = catch { throwable ->
     reportError(throwable as Exception)
 }
IgorGanapolsky
  • 26,189
  • 23
  • 116
  • 147