2

Issue

I have implemented the YouTube intent from a Fragment when a user clicks on an item in an app's RecyclerView cell. The click event is handled in xml via Data Binding and passed to the bound ViewModel which passes the LiveData value representing the click event to the Fragment.

startActivity(YouTubeIntents.createPlayVideoIntentWithOptions(activity, content.id, false, false))    

However, after triggering onBackPressed() to close the activity launched from YouTube and returning to the original app screen, the YouTube activity reappears when the screen is rotated as if the YouTube activity's finish() method has not been called.

Expected

Rotating the screen after closing the YouTubeActivity does not trigger the YouTubeActivity to re-show unexpectedly.

Attempted Solutions

  1. Experimented with changing the context passed into the Intent from context to activity.
  2. Called context.startActivity(...) from the Fragment as opposed to startActivity(...)
  3. Added a flag to the new activity intent: intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)as per this answer.
  4. Wrapped YouTube intent in a "headless" Fragment (a Fragment with no UI) in order to try and control the lifecycle.

1 Answer 1

1

Solution

This is not related to the YouTube API, but rather the Android Architecture library component LiveData. I am using a LiveData variable to pass a click event, which is being emitted again when the screen rotates.

The best solution is outlined by Jose Alcérreca in his Medium post LiveData with SnackBar, Navigation and other events (the SingleLiveEvent case).

In summary, Jose created an Event class that keeps track if the event has been handled.That way, when the screen is rotated the ViewModel and LiveData do not emit a value that is no longer valid for a single event.

Not the answer you're looking for? Browse other questions tagged or ask your own question.