Skip to content

Commit a928bf1

Browse files
committed
Create convertStreamToString.
Change-Id: I07dbb58813bc891f407773fddab7f1487f1ed24f
1 parent a888c87 commit a928bf1

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

core/network/src/main/kotlin/com/google/samples/apps/nowinandroid/core/network/demo/DemoNiaNetworkDataSource.kt

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,11 @@ import kotlinx.serialization.ExperimentalSerializationApi
3030
import kotlinx.serialization.json.Json
3131
import kotlinx.serialization.json.decodeFromStream
3232
import okio.use
33+
import java.io.ByteArrayOutputStream
34+
import java.io.InputStream
35+
import java.nio.charset.StandardCharsets
3336
import javax.inject.Inject
37+
import kotlin.coroutines.coroutineContext
3438

3539
/**
3640
* [NiaNetworkDataSource] implementation that provides static news resources to aid development
@@ -67,6 +71,21 @@ class DemoNiaNetworkDataSource @Inject constructor(
6771
override suspend fun getNewsResourceChangeList(after: Int?): List<NetworkChangeList> =
6872
getNewsResources().mapToChangeList(NetworkNewsResource::id)
6973

74+
private suspend fun convertStreamToString(inputStream: InputStream): String = withContext(
75+
coroutineContext,
76+
) {
77+
val result = ByteArrayOutputStream()
78+
val buffer = ByteArray(1024)
79+
var length = 0
80+
while (true) {
81+
length = inputStream.read(buffer)
82+
if (length == -1) break
83+
result.write(buffer, 0, length)
84+
}
85+
86+
result.toString(StandardCharsets.UTF_8.name())
87+
}
88+
7089
companion object {
7190
private const val NEWS_ASSET = "news.json"
7291
private const val TOPICS_ASSET = "topics.json"

0 commit comments

Comments
 (0)