Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/188.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何监视LiveData hasActiveObservers()?_Java_Android_Android Livedata - Fatal编程技术网

Java 如何监视LiveData hasActiveObservers()?

Java 如何监视LiveData hasActiveObservers()?,java,android,android-livedata,Java,Android,Android Livedata,我有MyRepository,它通过套接字从服务器获取实时提要 它通过一个可以从片段中观察到的MutableLiveData对象,将其数据提供给MyViewModel 为了避免浪费资源,我不希望MyRepository在没有观察者的情况下从服务器获取数据 我想知道如何监控MyRepository的MutableLiveData,因此如果没有观察者,那么MyRepository可以停止从服务器检索数据。类似地,如果添加了观察者,则可以(重新)开始数据检索 目前,我只是使用一个基本线程(请参见cre

我有MyRepository,它通过套接字从服务器获取实时提要

它通过一个可以从片段中观察到的MutableLiveData对象,将其数据提供给MyViewModel

为了避免浪费资源,我不希望MyRepository在没有观察者的情况下从服务器获取数据

我想知道如何监控MyRepositoryMutableLiveData,因此如果没有观察者,那么MyRepository可以停止从服务器检索数据。类似地,如果添加了观察者,则可以(重新)开始数据检索

目前,我只是使用一个基本线程(请参见
createobserversmonitorhread()
方法)作为监视器:

public class MyRepository {

    private static final String TAG = MyRepository.class.getSimpleName();

    private MutableLiveData<String> mutableLiveData;
    
    private Socket mSocket = null;

    public MyRepository(Application application) {

        mutableLiveData = new MutableLiveData<>();

        createSocket();
        
        createObserversMonitorThread();
    }

    private void createObserversMonitorThread() {

        Thread thread = new Thread() {

            @Override
            public void run() {

                try {
                    while (isAlive()) {

                        if (mutableLiveData.hasActiveObservers()) {

                            // We have observers, so connect to the server.
                            if (!mSocket.connected()) {
                                mSocket.connect();
                            }
                        }
                        else {

                            // We don't have observers, so disconnect from the server.
                            if (mSocket.connected()) {
                                mSocket.disconnect();
                            }
                        }

                        // Wait until next loop.
                        Thread.sleep(1000);
                    }
                }
                catch(Exception e) {

                    Log.e(TAG, "Exception", e);
                }
            }
        };

        thread.setName("MutableLiveData Observers Monitor");
        thread.setPriority(1);
        thread.setDaemon(true);
        thread.start();
    }

    public LiveData<String> getMutableLiveData() {
        return mutableLiveData;
    }

    /**
     * This method posts retrieved data to mutableLiveData.
     */
    private void createSocket() {

        try {
            mSocket = IO.socket(Constants.SERVER_URL);
            mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

                @Override
                public void call(Object... args) {

                    Log.d(TAG, "Connected.");
                }
            }).on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {

                @Override
                public void call(Object... args) {

                    if (args[0] instanceof Exception) {
                        Log.e(TAG, "Connect error: ", (Exception)args[0]);
                    }
                    else {
                        Log.e(TAG, "Connect error: " + args[0]);
                    }
                }

            }).on(Socket.EVENT_RECONNECT, new Emitter.Listener() {

                @Override
                public void call(Object... args) {

                    Log.d(TAG, "Reconnected.");
                }
            }).on(Socket.EVENT_RECONNECT_ERROR, new Emitter.Listener() {

                @Override
                public void call(Object... args) {

                    if (args[0] instanceof Exception) {
                        Log.e(TAG, "Reconnect error: ", (Exception)args[0]);
                    }
                    else {
                        Log.e(TAG, "Reconnect error: " + args[0]);
                    }
                }

            }).on(Socket.EVENT_MESSAGE, new Emitter.Listener() {

                @Override
                public void call(Object... args) {

                    //Log.d(TAG, "Data received.");

                    String s = (String) args[0];
                    mutableLiveData.postValue(s);
                }

            }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

                @Override
                public void call(Object... args) {
                    Log.d(TAG, "Disconnected.");
                }

            }).on(Socket.EVENT_ERROR, new Emitter.Listener() {

                @Override
                public void call(Object... args) {

                    if (args[0] instanceof Exception) {
                        Log.e(TAG, "Error: ", (Exception)args[0]);
                    }
                    else {
                        Log.e(TAG, "Error: " + args[0]);
                    }
                }

            });
        }
        catch(Exception e) {
            Log.e(TAG, "Could not create socket", e);
        }
    }
}
公共类MyRepository{
私有静态最终字符串标记=MyRepository.class.getSimpleName();
私有MutableLiveData MutableLiveData;
私有套接字mSocket=null;
公共MyRepository(应用程序){
mutableLiveData=新的mutableLiveData();
createSocket();
createObserversMonitorThread();
}
私有void CreateObserversMonitorhread(){
线程线程=新线程(){
@凌驾
公开募捐{
试一试{
while(isAlive()){
if(mutableLiveData.hasActiveObservers()){
//我们有观察员,所以连接到服务器。
如果(!mSocket.connected()){
mSocket.connect();
}
}
否则{
//我们没有观察员,因此请断开与服务器的连接。
if(mSocket.connected()){
mSocket.disconnect();
}
}
//等到下一个循环。
睡眠(1000);
}
}
捕获(例外e){
Log.e(标签“例外”,e);
}
}
};
setName(“MutableLiveData监视器”);
线程设置优先级(1);
setDaemon(true);
thread.start();
}
公共LiveData getMutableLiveData(){
返回可变的livedata;
}
/**
*此方法将检索到的数据发布到mutableLiveData。
*/
私有void createSocket(){
试一试{
mSocket=IO.socket(Constants.SERVER\uURL);
mSocket.on(Socket.EVENT_CONNECT,新的发射器.Listener(){
@凌驾
公共无效调用(对象…参数){
Log.d(标记“已连接”);
}
}).on(Socket.EVENT\u CONNECT\u错误,新发射器.Listener(){
@凌驾
公共无效调用(对象…参数){
if(args[0]instanceof Exception){
Log.e(标记“连接错误:”,(异常)参数[0]);
}
否则{
Log.e(标记“连接错误:+args[0]);
}
}
}).on(Socket.EVENT_重新连接,新发射器.Listener(){
@凌驾
公共无效调用(对象…参数){
Log.d(标签“重新连接”);
}
}).on(Socket.EVENT\u RECONNECT\u错误,新建发射器.Listener(){
@凌驾
公共无效调用(对象…参数){
if(args[0]instanceof Exception){
Log.e(标记“重新连接错误:”,(异常)参数[0]);
}
否则{
Log.e(标记“重新连接错误:+args[0]);
}
}
}).on(Socket.EVENT_消息,新发射器.Listener(){
@凌驾
公共无效调用(对象…参数){
//Log.d(标签“收到的数据”);
字符串s=(字符串)参数[0];
mutableLiveData.postValue;
}
}).on(Socket.EVENT_断开,新发射器.Listener(){
@凌驾
公共无效调用(对象…参数){
Log.d(标记“断开”);
}
}).on(Socket.EVENT_错误,新发射器.Listener(){
@凌驾
公共无效调用(对象…参数){
if(args[0]instanceof Exception){
Log.e(标记“Error:”,(异常)args[0]);
}
否则{
Log.e(标记“Error:+args[0]);
}
}
});
}
捕获(例外e){
Log.e(标记“无法创建套接字”,e);
}
}
}
这是可行的,但有更好的办法吗

更新

解决方案,感谢:

公共类MyRepository{
私有静态最终字符串标记=MyRepository.class.getSimpleName();
私有MutableLiveData MutableLiveData;
私有套接字mSocket=null;
公共MyRepository(应用程序){
createSocket();
mutableLiveData=新的mutableLiveData(){
@凌驾
受保护的void onActive(){
super.onActive();
//连接到服务器。这将(重新)启动在mutableLiveData上发布的数据。
如果(!mSocket.connected()){
mSocket.connect();
}
}
@凌驾
受保护的void onInactive(){
super.onInactive();
//断开与服务器的连接。这将停止在mutableLiveData上发布数据。
if(mSocket.connected()
public class MyRepository {

    private static final String TAG = MyRepository.class.getSimpleName();

    private MutableLiveData<String> mutableLiveData;

    private Socket mSocket = null;

    public MyRepository(Application application) {

        createSocket();

        mutableLiveData = new MutableLiveData<String>() {

            @Override
            protected void onActive() {
                super.onActive();

                // Connect to server. This will (re)start data being posted on mutableLiveData.
                if (!mSocket.connected()) {
                    mSocket.connect();
                }
            }

            @Override
            protected void onInactive() {
                super.onInactive();

                // Disconnect from server. This will stop data being posted on mutableLiveData.
                if (mSocket.connected()) {
                    mSocket.disconnect();
                }
            }
        };
    }

    public LiveData<String> getMutableLiveData() {
        return mutableLiveData;
    }

    /**
     * This method posts retrieved data to mutableLiveData.
     */
    private void createSocket() {
        // Same code as before.
    }
}