1

I am following this post: https://stackoverflow.com/questions/56071990/android-architecture-singleliveevent-and-eventobserver-practicle-example-in-java

public class Event<T> {
    private boolean hasBeenHandled = false;
    private T content;

    public Event(T content) {
        this.content = content;
    }

    public T getContentIfNotHandled() {
        if (hasBeenHandled) {
            return null;
        } else {
            hasBeenHandled = true;
            return content;
        }
    }

    public boolean isHandled() {
        return hasBeenHandled;
    }
}

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

public class EventObserver<T> implements Observer<Event<T>> {
    private OnEventChanged onEventChanged;

    public EventObserver(OnEventChanged onEventChanged) {
        this.onEventChanged = onEventChanged;
    }

    @Override
    public void onChanged(@Nullable Event<T> tEvent) {
        if (tEvent != null && tEvent.getContentIfNotHandled() != null && onEventChanged != null)
            onEventChanged.onUnhandledContent(tEvent.getContentIfNotHandled());
    }

    interface OnEventChanged<T> {
        void onUnhandledContent(T data);
    }
}

I have this in my repository:

private MutableLiveData<Event<String>> _amsRepositoryError = new MutableLiveData<>();
public MutableLiveData<Event<UserModel>> amsLoginSuccessReply(){return _amsLoginSuccessReply;}

_amsLoginSuccessReply.postValue(new Event(userModel));

And I catch this in my viewmodel:

amsRepository.amsLoginSuccessReply().observe(mLifeCycleOwner, new EventObserver<UserModel>(data -> {
           // HOW DO I GET THE data here.
        }));

on the observe, how do I get the values of the data?

Ibanez1408
  • 4,550
  • 10
  • 59
  • 110

1 Answers1

1

I know its too late, but it may help someone else, you should get results but in the EventObserver class, in onChanged method, you are hitting tEvent.getContentIfNotHandled() twice and when you hit it once in the Event class, hasBeenHandled is set to true and that's why you are getting null.

Replace your onChanged method to this

 @Override
public void onChanged(@Nullable Event<T> tEvent) {
    if (tEvent != null) {
        Object content = tEvent.getContentIfNotHandled();
        if (content != null && onEventChanged != null) {
            onEventChanged.onUnhandledContent(content);
        }
    }
}
FK Khan
  • 116
  • 4