Search code examples
couchdbcouchbase-lite

Monitoring the replication process on CouchDB


I have a project with CouchDB and couchbase-lite on Android. I have an Activitiy ,lets say ReplicationActivity, where I am showing a ProgressDialog while the replication process run, this process uses around 2 hours. My plan is when the replication process is finished the app moves the user to the MainActivity.
The problem I have is that the app moves to MainActivity before the process is finished, so I have not all the data available on MainActivity

In order to monitoring the replication process I am doing this:

CouchbaseManager.getInstance().addProgressListener(new Replication.ChangeListener() {
        @Override
        public void changed(Replication.ChangeEvent event) {

            if (CouchbaseManager.getInstance().getReplicationProgress() > 0 &&
                    CouchbaseManager.getInstance().getReplicationTotal() > 0 &&
                    CouchbaseManager.getInstance().getReplicationTotal() ==
                    CouchbaseManager.getInstance().getReplicationProgress() &&
                    CouchbaseManager.getInstance().getPullwork().getStatus() !=
                            Replication.ReplicationStatus.REPLICATION_ACTIVE &&
                    CouchbaseManager.getInstance().getPushwork().getStatus() !=
                            Replication.ReplicationStatus.REPLICATION_ACTIVE &&
                    CouchbaseManager.getInstance().getPullmaster().getStatus() !=
                            Replication.ReplicationStatus.REPLICATION_ACTIVE) {
                if (mProgressDialog != null && mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                    Log.i("usercontroller", "MOVING TO MAIN ACTIVITY");


                }

Any idea about what I can do in order to know the when replication process is finished?


Solution

  • You want to look at the ChangeEvent object passed to the listener.

    Here's an example on how to detect a replication finishing:

    // Replication.ChangeListener
    @Override
    public void changed(Replication.ChangeEvent changeEvent) {
      if (changeEvent.getError() != null) {
        Throwable lastError = changeEvent.getError();
    
        // React to the error
    
        return;
      }
    
      if (changeEvent.getTransition() == null) return;
    
      ReplicationState dest = changeEvent.getTransition().getDestination();
    
      replicationActive = ((dest == ReplicationState.STOPPING || dest == ReplicationState.STOPPED) ? false : true);
    
      stateListeners.forEach(listener -> listener.onChange(replicationActive));
    }
    

    You can find more background and discussion of the code in this blog.