Skip to content

Commit 538edef

Browse files
Use external API and coroutines to get real video information
1 parent 8d70792 commit 538edef

File tree

1 file changed

+28
-8
lines changed

1 file changed

+28
-8
lines changed

src/main/kotlin/App.kt

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,26 @@
1+
import kotlinx.coroutines.async
12
import kotlinx.css.*
23
import react.*
34
import react.dom.*
45
import styled.css
56
import styled.styledDiv
7+
import kotlin.browser.window
8+
import kotlinx.coroutines.*
9+
10+
suspend fun fetchVideo(id: Int): Video =
11+
window.fetch("https://my-json-server.typicode.com/kotlin-hands-on/kotlinconf-json/videos/$id")
12+
.await()
13+
.json()
14+
.await()
15+
.unsafeCast<Video>()
16+
17+
suspend fun fetchVideos(): List<Video> = coroutineScope {
18+
(1..25).map { id ->
19+
async {
20+
fetchVideo(id)
21+
}
22+
}.awaitAll()
23+
}
624

725
external interface AppState : RState {
826
var currentVideo: Video?
@@ -12,14 +30,16 @@ external interface AppState : RState {
1230

1331
class App : RComponent<RProps, AppState>() {
1432
override fun AppState.init() {
15-
unwatchedVideos = listOf(
16-
Video(1, "Building and breaking things", "John Doe", "https://youtu.be/PsaFVLr8t4E"),
17-
Video(2, "The development process", "Jane Smith", "https://youtu.be/PsaFVLr8t4E"),
18-
Video(3, "The Web 7.0", "Matt Miller", "https://youtu.be/PsaFVLr8t4E")
19-
)
20-
watchedVideos = listOf(
21-
Video(4, "Mouseless development", "Tom Jerry", "https://youtu.be/PsaFVLr8t4E")
22-
)
33+
unwatchedVideos = listOf()
34+
watchedVideos = listOf()
35+
36+
val mainScope = MainScope()
37+
mainScope.launch {
38+
val videos = fetchVideos()
39+
setState {
40+
unwatchedVideos = videos
41+
}
42+
}
2343
}
2444

2545
override fun RBuilder.render() {

0 commit comments

Comments
 (0)