Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use LiveData without Lifecycle Owner

I could not find any information, if it's a bad idea to use LiveData without a lifecycle owner. And if it is, what could be the alternative?

Let me give you just a simple example

class Item() {
    private lateinit var property: MutableLiveData<Boolean>

    init {
        property.value = false
    }

    fun getProperty(): LiveData<Boolean> = property

    fun toggleProperty() {
        property.value = when (property.value) {
            false -> true
            else -> false
        }
    }
}

class ItemHolder {

    private val item = Item()

    private lateinit var observer: Observer<Boolean>

    fun init() {
        observer = Observer<Boolean> { item ->
            updateView(item)
        }
        item.getProperty().observeForever(observer)
    }

    fun destroy() {
        item.getProperty().removeObserver(observer)
    }

    fun clickOnButton() {
        item.toggleProperty();
    }

    private fun updateView(item: Boolean?) {
        // do something
    }
}
like image 715
Tima Avatar asked Apr 30 '18 15:04

Tima


3 Answers

You can register an observer without an associated LifecycleOwner object using the

observeForever(Observer) method

like that:

 orderRepo.getServices().observeForever(new Observer<List<Order>>() {
            @Override
            public void onChanged(List<Order> orders) {
               //
            }
        });
like image 163
Mohamed AbdelraZek Avatar answered Nov 05 '22 10:11

Mohamed AbdelraZek


You can register an observer without an associated LifecycleOwner object using the observeForever(Observer) method. In this case, the observer is considered to be always active and is therefore always notified about modifications. You can remove these observers calling the removeObserver(Observer) method.

Ref https://developer.android.com/topic/libraries/architecture/livedata.html#work_livedata

like image 4
alizx Avatar answered Nov 05 '22 11:11

alizx


For me LiveData has two benefits:

  1. It aware of life cycle events and will deliver updates only in an appropriate state of a subscriber (Activity/Fragment).
  2. It holds the last posted value, and updates with it new subscribers.

As already been said, if you're using it out of the life cycle components (Activity/Fragment) and the delivered update could be managed anytime, then you can use it without life cycle holder, otherwise, sooner or later, it may result in a crash, or data loss.

As an alternative to the LiveData behavior, I can suggest a BehaviourSubject from RxJava2 framework, which acts almost the same, holding the last updated value, and updating with it new subscribers.

like image 3
Demigod Avatar answered Nov 05 '22 09:11

Demigod