• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

cashapp/zipline: Run Kotlin/JS libraries in Kotlin/JVM and Kotlin/Native program ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

cashapp/zipline

开源软件地址(OpenSource Url):

https://github.com/cashapp/zipline

开源编程语言(OpenSource Language):

C 74.9%

开源软件介绍(OpenSource Introduction):

Zipline

This library streamlines using Kotlin/JS libraries from Kotlin/JVM and Kotlin/Native programs. It makes it fetching code as easy as fetching data:

  • For continuous deployment within mobile apps, just like we do for servers and web apps. It'd be simpler to do continuous deploys via the app stores! But that process is too slow and we can't guarantee that user’s devices will update immediately.
  • For user-customizable behavior and plugin systems
  • For updating business rules, like pricing or payments
  • For fresh content like games

Zipline works by embedding the QuickJS JavaScript engine in your Kotlin/JVM or Kotlin/Native program. It's a small and fast JavaScript engine that's well-suited to embedding in applications.

(Looking for Duktape Android?)

Code Example

Let's make a trivia game that has fresh questions every day, even if our users don't update their apps. We define our interface in commonMain so that we can call it from Kotlin/JVM and implement it in Kotlin/JS.

interface TriviaService : ZiplineService {
  fun games(): List<TriviaGame>
  fun answer(questionId: String, answer: String): AnswerResult
}

Next we implement it in jsMain:

class RealTriviaService : TriviaService {
  // ...
}

Let's connect the implementation running in Kotlin/JS to the interface running in Kotlin/JVM. In jsMain we define an exported function to bind the implementation:

@JsExport
fun launchZipline() {
  val zipline = Zipline.get()
  zipline.bind<TriviaService>("triviaService", RealTriviaService())
}

Now we can start a development server to serve our JavaScript to any running applications that request it.

$ ./gradlew samples:trivia:trivia-js:jsBrowserProductionRun --info --continuous

Note that this Gradle won't ever reach 100%. That's expected; we want the development server to stay on. Also note that the --continuous flag will trigger a re-compile whenever the code changes.

You can see the served application manifest at localhost:8080/manifest.zipline.json. It references all the code modules for the application.

In jvmMain we need write a program that downloads our Kotlin/JS code and calls it. We use ZiplineLoader which handles code downloading, caching, and loading. We create a Dispatcher to run Kotlin/JS on. This must be a single-threaded dispatcher as each Zipline instance must be confined to a single thread.

suspend fun launchZipline(dispatcher: CoroutineDispatcher): Zipline {
  val manifestUrl = "http://localhost:8080/manifest.zipline.json"
  val loader = ZiplineLoader(dispatcher, OkHttpClient())
  return loader.loadOrFail("trivia", manifestUrl) {
    val moduleName = "./zipline-root-trivia-js.js"
    it.quickJs.evaluate(
      "require('$moduleName').app.cash.zipline.samples.trivia.launchZipline()",
      "launchZiplineJvm.kt"
    )
  }
}

Now we build and run the JVM program to put it all together. Do this in a separate terminal from the development server!

$ ./gradlew samples:trivia:trivia-host:shadowJar
java -jar samples/trivia/trivia-host/build/libs/trivia-host-1.0.0-SNAPSHOT-all.jar

Interface bridging

Zipline makes it easy to share interfaces with Kotlin/JS. Define an interface in commonMain, implement it in Kotlin/JS, and call it from the host platform. Or do the opposite: implement it on the host platform and call it from Kotlin/JS.

Bridged interfaces must extend ZiplineService, which defines a single close() method to release held resources.

By default, arguments and return values are pass-by-value. Zipline uses kotlinx.serialization to encode and decode values passed across the boundary.

Interface types that extend from ZiplineService are pass-by-reference: the receiver may call methods on a live instance.

Interface functions may be suspending. Internally Zipline implements setTimeout() to make asynchronous code work as it's supposed to in Kotlin/JS.

Zipline also supports Flow<T> as a parameter or return type. This makes it easy to build reactive systems.

Fast

One potential bottleneck of embedding JavaScript is waiting for the engine to compile the input source code. Zipline precompiles JavaScript into efficient QuickJS bytecode to eliminate this performance penalty.

Another bottleneck is waiting for code to download. Zipline addresses this with support for modular applications. Each input module (Like Kotlin's standard, serialization, and coroutines libraries) is downloaded concurrently. Each downloaded module is cached. Modules can also be embedded with the host application to avoid any downloads if the network is unreachable. If your application module changes more frequently than your libraries, users only download what's changed.

If you run into performance problems in the QuickJS runtime, Zipline includes a sampling profiler. You can use this to get a breakdown of how your application spends its CPU time.

Developer-Friendly

Zipline implements console.log by forwarding messages to the host platform. It uses android.util.Log on Android, java.util.logging on JVM, and stdout on Kotlin/Native.

Zipline integrates Kotlin source maps into QuickJS bytecode. If your process crashes, the stacktrace will print .kt files and line numbers. Even though there's JavaScript underneath, developers don't need to interface with .js files.

After using a bridged interface it must be closed so the peer object can be garbage collected. This is difficult to get right, so Zipline borrows ideas from LeakCanary and aggressively detects when a close() call is missed.

Requirements

Zipline works on Android 4.3+ (API level 18+), Java 8+, and Kotlin/Native.

Zipline uses unstable APIs in its implementation and is sensitive to version updates for these components.

Component Supported Version Notes
Kotlin Compiler 1.6.21 Kotlin compiler plugins do not yet have a stable API.
Kotlin Coroutines 1.6.1-native-mt For invokeOnClose().
Kotlin Serialization 1.3.3 For decodeFromDynamic(), encodeToDynamic(), EmptySerializersModule, and ContextualSerializer.

We intend to use stable APIs as soon as they are available.

We intend to keep Zipline host and runtime releases interoperable so you can upgrade each independently.

Host Zipline Version Supported Runtime Zipline Versions
0.x Exact same 0.x version as the host.
1.x Any 1.x version.

License

Copyright 2015 Square, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Duktape-Android

This project was previously known as Duktape-Android and packaged the Duktape JavaScript engine for Android. The Duktape history is still present in this repo as are the release tags. Available versions are listed on Maven central.




鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
saadq/resumake.io: 发布时间:2022-07-09
下一篇:
dnl-blkv/mcdowell-cv: A Nice-looking CV template made into LaTeX发布时间:2022-07-09
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap