Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

React Native: Is it possible to get the return value of a JavaScript fuction from Java?

I've been scouring the Internet so much but I can't find a solution for this seemingly simple problem. Basically, I have a function like this in JavaScript:

function getCookies(url: string): Cookie[] {
}

and a function like this in Java:

List<Cookie> loadForRequest(HttpUrl url) {
}

and I want the Java method to call into the JavaScript method and use its result. After spending hours researching this problem though I still have zero idea how to do this. I found this question which I thought would be helpful, but the class it mentions (CatalystInstance) doesn't let you see the return values of functions. I also tried a hackish workaround using events, see below:

private static final Map<Pair<String, String>, List<Cookie>> sLoadForRequestResults = new HashMap<>();

@Override
public List<Cookie> loadForRequest(HttpUrl url) {
    WritableMap event = Arguments.createMap();
    event.putString("jarId", mId);
    event.putString("url", url.toString());
    sendEvent("request_getCookies", event);

    return sLoadForRequestResults.get(new Pair(mId, url.toString()));
}

@ReactMethod
public void respond_getCookies(String jarId, String url, ReadableArray cookies) {
    List<Cookie> bakedCookies = new ArrayList<>();
    for (int i = 0; i < cookies.size(); i++) {
        bakedCookies.add(toOkHttpCookie(cookies.getMap(i)));
    }
    sLoadForRequestResults.put(new Pair(jarId, url), bakedCookies);
}

// In my JS file

const {CustomCookiesModule} = NativeModules;

const eventEmitter = new NativeEventEmitter(CustomCookiesModule);
eventEmitter.addListener('request_getCookies', (event) => {
    console.log('request_getCookies', event);

    const {jarId, url} = event;
    const jar = CookieJarManager.get(jarId);
    const cookies = jar.getCookiesSync(url);
    CustomCookiesModule.respond_getCookies(jarId, url, cookies);
});

Basically the idea was that my Java code would emit an event to trigger the JS code, the JS code would run and call the Java code back in order to store the results in a static object, then I would return the results stored in the static object. But even this approach is not working-- I am seeing that return sLoadForRequestResults.get(new Pair(mId, url.toString())) runs before respond_getCookies does, because apparently sendEvent doesn't wait for the handlers to actually finish.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...