suspend fun dataFlowFromDbAndApi( fromDb: suspend () -> Either, shouldUpdate: (old: Type, new: Type) -> Boolean, fromApi: suspend () -> Either, saveDataFromApi: suspend (Type) -> Either ): Flow> = flow { val dbData = fromDb() when { !isOnline() -> { when (dbData) { is Either.Left -> emit(dbData.value.left()) is Either.Right -> emit(dbData.value.right()) } } isOnline() && dbData is Either.Left -> { when (val apiData = fromApi()) { is Either.Left -> { emit(apiData.value.left()) } is Either.Right -> { emit(apiData.value.right()) saveDataFromApi(apiData.value) } } } isOnline() && dbData is Either.Right -> { emit(dbData.value.right()) when (val apiData = fromApi()) { is Either.Left -> { emit(apiData.value.left()) } is Either.Right -> { if (shouldUpdate(dbData.value, apiData.value) && dbData != apiData) { emit(apiData.value.right()) saveDataFromApi(apiData.value) } } } } } } private fun isOnline() = network.currentState() == NetworkState.CONNECTED }