简体   繁体   中英

kotlin-multiplatform : how to use Kotlin Flow in Javascript

I have created a kotlin multi-platform library to design Domain layer that targets JVM and JS (nodejs and browser). Domain depends on UseCase, UseCase depends on Repository, Repository depends on Service and Database. AFAIK, Kotlin Coroutines work across platforms (JS/JVM/Native).

I have a function that returns Flow , instead of Promise .

fun getUserList() : Flow<List<User>>{...}

Reason is, I want to update UI as soon as there is any change in Database. On JVM (or Android), I know how to consume Flow. But don't understand how to consume it from plain Javascript(or TypeScript) (not Kotlin-JS). Even I didn't find any supporting article that explains about using Flow for JS.

Can anyone help me out with this? Any help will be appreciated!

PS: My Javascript Skills are intermediate:P

So, till I find some official solution to this problem, here is what I have come up with:

Instead of returning Flow, I created a wrapper function take two arguments:

@JsName("getUsersListWithUpdatesJs")
fun UserUseCase.getUsersListWithUpdatesJs(
    success: (List<User>) -> Unit,
    error: (Throwable) -> Unit
) = GlobalScope.promise {
    try {
        getUsersList().collect {
            success(it)
        }
    } catch (exception: Throwable) {
        error(exception)
    }
}

Then I published the Js library on our Nexus Server.

Added as dependency into JS project using npm.

Then, the usage:

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);
      }
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM