AbstractRocketChatCacheObserver.java 1.76 KB
Newer Older
1 2 3
package chat.rocket.android.service.internal;

import android.content.Context;
Tiago Cunha's avatar
Tiago Cunha committed
4

5 6
import com.hadisatrio.optional.Optional;

7
import chat.rocket.android.log.RCLog;
Tiago Cunha's avatar
Tiago Cunha committed
8
import io.reactivex.disposables.CompositeDisposable;
Yusuke Iwaki's avatar
Yusuke Iwaki committed
9

10 11
import chat.rocket.android.RocketChatCache;
import chat.rocket.android.helper.TextUtils;
Tiago Cunha's avatar
Tiago Cunha committed
12
import chat.rocket.persistence.realm.models.ddp.RealmRoom;
Tiago Cunha's avatar
Tiago Cunha committed
13
import chat.rocket.persistence.realm.RealmHelper;
14
import chat.rocket.android.service.Registrable;
15

16
public abstract class AbstractRocketChatCacheObserver implements Registrable {
17 18 19
  private final Context context;
  private final RealmHelper realmHelper;
  private String roomId;
Tiago Cunha's avatar
Tiago Cunha committed
20
  private CompositeDisposable compositeDisposable = new CompositeDisposable();
21 22 23 24 25 26

  protected AbstractRocketChatCacheObserver(Context context, RealmHelper realmHelper) {
    this.context = context;
    this.realmHelper = realmHelper;
  }

Tiago Cunha's avatar
Tiago Cunha committed
27
  private void updateRoomIdWith(String roomId) {
28
    if (!TextUtils.isEmpty(roomId)) {
Tiago Cunha's avatar
Tiago Cunha committed
29 30
      RealmRoom room = realmHelper.executeTransactionForRead(realm ->
          realm.where(RealmRoom.class).equalTo("rid", roomId).findFirst());
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
      if (room != null) {
        if (this.roomId == null || !this.roomId.equals(roomId)) {
          this.roomId = roomId;
          onRoomIdUpdated(roomId);
        }
        return;
      }
    }

    if (this.roomId != null) {
      this.roomId = null;
      onRoomIdUpdated(null);
    }
  }

  protected abstract void onRoomIdUpdated(String roomId);

Yusuke Iwaki's avatar
Yusuke Iwaki committed
48 49
  @Override
  public final void register() {
Tiago Cunha's avatar
Tiago Cunha committed
50 51 52
    compositeDisposable.add(
        new RocketChatCache(context)
            .getSelectedRoomIdPublisher()
53
            .map(Optional::get)
54
            .subscribe(this::updateRoomIdWith, RCLog::e)
Tiago Cunha's avatar
Tiago Cunha committed
55
    );
56 57
  }

Yusuke Iwaki's avatar
Yusuke Iwaki committed
58 59
  @Override
  public final void unregister() {
Tiago Cunha's avatar
Tiago Cunha committed
60
    compositeDisposable.clear();
61 62
  }
}