Skip to content

Commit

Permalink
Add printFlow method
Browse files Browse the repository at this point in the history
  • Loading branch information
janseeger committed Sep 29, 2023
1 parent 786df04 commit 691c7e9
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package de.sipgate.waffeleisen.flow

import android.util.Log
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

inline fun <T> Flow<T?>.printFlow(
tag: String = "from flow",
crossinline printFunc: (String) -> Unit = { content -> Log.d(tag, content) },
crossinline stringFunc: (T?) -> String? = { it.toString() }
) = map {
printFunc(stringFunc(it) ?: "null")
it
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package de.sipgate.waffeleisen.flow

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test

class PrintFlowKtTest {

@Test
fun printFlowPassesThroughValuesTransparently() = runTest {
val flow = flowOf("first", "second", "third")

val result = flow
.printFlow(printFunc = { println(it) })
.collectAsList()

assertEquals(listOf("first", "second", "third"), result)
}

@Test
fun printFlowExecutesPrintFuncOnceForEachEmittedValue() = runTest {
val flow = flowOf("first", "second", "third")

val result = mutableListOf<String>()
flow.printFlow(printFunc = { result.add(it) }).collect()

assertEquals(listOf("first", "second", "third"), result.toList())
}

@Test
fun printFlowExecutesStringFuncForEachEmittedValue() = runTest {
val flow = flowOf("first", "second", "third")

val result = mutableListOf<String>()
flow.printFlow(
printFunc = { /* dummy */ },
stringFunc = { result.add(it!!); it }
).collect()

assertEquals(listOf("first", "second", "third"), result.toList())
}

@Test
fun printFlowCallsToStringByDefault() = runTest {
data class SomeData(
val aProperty: String,
val bProperty: Boolean
)

val flow = flowOf(
SomeData("asdf", true),
SomeData("wah", false)
)

val stringBuffer = StringBuffer()
flow.printFlow(printFunc = { stringBuffer.append(it).append("\n") })
.collect()

val expected = """
SomeData(aProperty=asdf, bProperty=true)
SomeData(aProperty=wah, bProperty=false)
""".trimIndent()

assertEquals(expected, stringBuffer.toString())
}

private suspend fun <T> Flow<T>.collectAsList() =
mutableListOf<T>().apply {
this@collectAsList.map(this::add).collect()
}
}

0 comments on commit 691c7e9

Please sign in to comment.