title: Java extension methods for LiveData
body: <p>In Kotlin there's an extension method observeOnce (<a href="https://code.luasoftware.com/tutorials/android/android-livedata-observe-once-only-kotlin/" rel="nofollow noreferrer">https://code.luasoftware.com/tutorials/android/android-livedata-observe-once-only-kotlin/</a>) which is the behaviour I'm looking to replicate in Java. It's to my understanding from googling that you can't use Kotlin extension methods in java (may be wrong), so I've got two options of using SingleEventLiveData which I've implemented and am not keen on, and removing my observer once used;</p>
  
  <pre><code>final LiveData&lt;List&lt;String&gt;&gt; stringsLiveData = mViewModel.getStrings();
  
  stringsliveData.observe(getViewLifecycleOwner(), strings -&gt; {
      // Do stuff with data here
      stringsLiveData.removeObservers(getViewLifecycleOwner());
  });
  </code></pre>
  
  <p>Is there an equivilant method that can be used as the link above so;</p>
  
  <pre><code>mViewModel.getStrings().observeOnce(getViewLifecycleOwner(), strings -&gt; {
      //Do stuff here
  });
  </code></pre>
  
  <p><strong>Edit</strong>: As per the accepted answer below (modified to compile) I've got;</p>
  
  <pre><code>class LiveDataUtils {
      public static &lt;T&gt; void observeOnce(LiveData&lt;T&gt; liveData, Observer&lt;T&gt; observer) {
          liveData.observeForever(o -&gt; {
              liveData.removeObserver(observer);
              observer.onChanged(o);
          });
      }
  }
  </code></pre>
  
  <p>and a simple usage of this;</p>
  
  <pre><code>LiveDataUtils.observeOnce(
      mViewModel.getStrings(),
      strings -&gt; {
          // Do some work here
      }
  );
  </code></pre>