Skip to content

Commit 80172dc

Browse files
committed
Replace manual string converter to readText method.
Change-Id: If8cc6c27bd399fcdf8446ec411626f13d39e707c
1 parent 301f7f5 commit 80172dc

File tree

1 file changed

+2
-24
lines changed

1 file changed

+2
-24
lines changed

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

Lines changed: 2 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,7 @@ import kotlinx.coroutines.withContext
2929
import kotlinx.serialization.ExperimentalSerializationApi
3030
import kotlinx.serialization.json.Json
3131
import kotlinx.serialization.json.decodeFromStream
32-
import java.io.ByteArrayOutputStream
33-
import java.io.InputStream
34-
import java.nio.charset.StandardCharsets
3532
import javax.inject.Inject
36-
import kotlin.coroutines.coroutineContext
3733

3834
/**
3935
* [NiaNetworkDataSource] implementation that provides static news resources to aid development
@@ -52,7 +48,7 @@ class DemoNiaNetworkDataSource @Inject constructor(
5248
} else {
5349
// Use decodeFromString to capability with API 24 below.
5450
// https://github.com/Kotlin/kotlinx.serialization/issues/2457#issuecomment-1786923342
55-
val topicsJsonString = convertStreamToString(assets.open(TOPICS_ASSET))
51+
val topicsJsonString = assets.readText(TOPICS_ASSET)
5652
networkJson.decodeFromString(topicsJsonString)
5753
}
5854
}
@@ -65,7 +61,7 @@ class DemoNiaNetworkDataSource @Inject constructor(
6561
} else {
6662
// Use decodeFromString to capability with API 24 below.
6763
// https://github.com/Kotlin/kotlinx.serialization/issues/2457#issuecomment-1786923342
68-
val newsJsonString = convertStreamToString(assets.open(NEWS_ASSET))
64+
val newsJsonString = assets.readText(NEWS_ASSET)
6965
networkJson.decodeFromString(newsJsonString)
7066
}
7167
}
@@ -76,24 +72,6 @@ class DemoNiaNetworkDataSource @Inject constructor(
7672
override suspend fun getNewsResourceChangeList(after: Int?): List<NetworkChangeList> =
7773
getNewsResources().mapToChangeList(NetworkNewsResource::id)
7874

79-
/**
80-
* Convert [InputStream] to [String].
81-
*/
82-
private suspend fun convertStreamToString(inputStream: InputStream): String = withContext(
83-
coroutineContext,
84-
) {
85-
val result = ByteArrayOutputStream()
86-
val buffer = ByteArray(1024)
87-
var length: Int
88-
while (true) {
89-
length = inputStream.read(buffer)
90-
if (length == -1) break
91-
result.write(buffer, 0, length)
92-
}
93-
94-
result.toString(StandardCharsets.UTF_8.name())
95-
}
96-
9775
companion object {
9876
private const val NEWS_ASSET = "news.json"
9977
private const val TOPICS_ASSET = "topics.json"

0 commit comments

Comments
 (0)