简体   繁体   中英

Subscribe to Observable returning wrong values

I'm building an application using Electron . My file structure looks like this, all folder are in the same directory. My problem is that, when I subscribe to startActivity method, I get back two different values. It looks like the singleton is not working and I'm getting back two different instances of an object.

Folder structure

- activity.ts
- main.ts
- renderer.ts

renderer.ts

import Activity from "./activity";

const activity = Activity.getInstance();

activity.startActivity().subscribe(
    data => {
        console.log("Renderer: " + data);
    }
);

activity.ts

import {Observable} from 'rxjs/Rx';


class Activity {
    private static _instance: Activity;

    public static getInstance() {
        return this._instance || (this._instance = new this());
    }

    public startActivity() {
        return Observable
            .interval(this.config.timeInterval)
            .map(() => {
                return Math.random();
            });
    }
}

export default Activity;

main.ts

import {app} from "electron";


app.on("ready", () => {

    const activity = Activity.getInstance();
    activity.startActivity().subscribe(
        data => {
            console.log("Main: " + data);
        }
    );
});

Results

Renderer: 0.599276120749491
Main: 0.5746604589633764

So, why am I not getting the same data from both console.log() calls?
PS: I'm quite new to Node.js world, so I'm sure it's something trivial..

It's cause of Electron's architecture based on multi process. Main / Renderer runs on different process , means you can't directly share object between as same as doesn't provide singleton object as well, cause main process creates one object and renderer process also creates one for is own as well. If you'd like to establish single state between process, you should consider synchronization via passing values between ipc protocol.

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