Stage 1 changes - Xantier/multiplat-workshop GitHub Wiki
-
Adding new modules (new lines to
settings.gradle
):multiplat-workshop-js
multiplat-workshop-jvm
-
Modifying
ApiClient
class inmultiplat-workshop-common
to be a common (expect) class. -
Creating actual classes for both JVM and JS
-
build.gradle
- Adding platform-jvm plugin to indicate this is a JVM impl of multiplatform common
- Adding okhttp dependency
apply plugin: 'kotlin-platform-jvm'
dependencies {
expectedBy project(":multiplat-workshop-common")
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compile "com.squareup.okhttp3:okhttp:$okhttp_version"
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
- ApiClient.kt
- Making call to our meetup endpoint
actual class ApiClient {
actual fun fetchPhotos(): String {
val client = OkHttpClient()
val request = Request.Builder()
.url(PHOTO_URL)
.build()
val response = client.newCall(request).execute()
val returnable = response.body()?.string() ?: ""
println(returnable)
return returnable
}
}
- build.gradle
- https://kotlinlang.org/docs/tutorials/javascript/getting-started-gradle/getting-started-with-gradle.html
- Note that we are dumping everything to web dir and fetching them from there. We'll create a proper bundle in later stages.
apply plugin: 'kotlin-platform-js'
dependencies {
expectedBy project(":multiplat-workshop-common")
compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version"
compile "org.jetbrains.kotlinx:kotlinx-coroutines-core-js:$coroutines_version"
}
compileKotlin2Js {
kotlinOptions.outputFile = "${projectDir}/web/bundle.js"
kotlinOptions.moduleKind = 'umd'
}
task assembleWeb(type: Sync) {
configurations.compile.each { File file ->
from(zipTree(file.absolutePath), {
includeEmptyDirs = false
include { fileTreeElement ->
def path = fileTreeElement.path
path.endsWith(".js") && (path.startsWith("META-INF/resources/") ||
!path.startsWith("META-INF/"))
}
})
}
from compileKotlin2Js.destinationDir
into "${projectDir}/web"
dependsOn classes
}
assemble.dependsOn assembleWeb
kotlin {
experimental {
coroutines = "enable"
}
}
- ApiClient.kt - Our multiplatform common's actual implementation
const val CORS_ANYWHERE = "https://cors-anywhere.herokuapp.com/"
actual class ApiClient {
actual fun fetchPhotos(): String {
launch{
val response = window.fetch(CORS_ANYWHERE + PHOTO_URL, object : RequestInit {
override var headers: dynamic = json(
"Accept" to "application/json",
"Content-Type" to "application/json")
}).await()
val jsonResponse = response.text().await()
println(jsonResponse)
}
return "null"
}
}
- index.kt
call that ApiClient
- web/index.html
<html>
<body>
<script src="kotlin.js"></script>
<script src="kotlinx-coroutines-core-js.js"></script>
<script src="bundle.js"></script>
</body>
</html>