我创建了一个kotlin多平台库来设计针对JVM和JS(nodejs和浏览器)的Domain层。域取决于UseCase,UseCase取决于存储库,存储库取决于服务和数据库。 AFAIK,Kotlin Coroutines可跨平台工作(JS / JVM / Native)。
我有一个返回Flow
而不是Promise
的函数。
fun getUserList() : Flow<List<User>>{...}
原因是,我想在数据库中有任何更改时立即更新UI。在JVM(或Android)上,我知道如何使用Flow。但是不了解如何从普通Javascript(或TypeScript)(不是Kotlin-JS)使用它。甚至我也找不到任何支持文章,说明如何使用Flow for JS。
有人可以帮我吗?任何帮助将不胜感激!
PS:我的Java技能是中等的:P
所以,直到我找到解决这个问题的正式方法,这是我想出的:
不是返回Flow,而是创建了一个带有两个参数的包装器函数:
@JsName("getUsersListWithUpdatesJs")
fun UserUseCase.getUsersListWithUpdatesJs(
success: (List<User>) -> Unit,
error: (Throwable) -> Unit
) = GlobalScope.promise {
try {
getUsersList().collect {
success(it)
}
} catch (exception: Throwable) {
error(exception)
}
}
然后我在Nexus服务器上发布了Js库。
使用npm作为依赖项添加到JS项目中。
然后,用法:
import * as domain from "my-multiplatform-library";
…
…
…
domain.com.abc.usecase.createUserUseCaseJs().then(
(useCase) => {
console.log(useCase);
useCase. getUsersListWithUpdatesJs(
(list) => {
// This block should be called twice. For Empty and Non-empty array
console.log("Response", list)
},
(error) => {
// Ignore this block for now
},
);
},
(error) => {
console.log(error);
}
);