I am using LiveData with Activity. Everything is working when I test on Android 7, but has issues when I test on lower Android SDK versions.
- When I close app, send some messages, then open app again, I am fetching received values from ViewModel via LiveData.
- But if I open new activity over current one, receive some messages in ViewModel, and return back to that activity I am not getting those messages in Activity.
In first case onPause
, onStop
then onStart
, onResume
is called. In second case onPause
then onResume
is called. Also in second case I have active observer, but I am not getting received messages.
ChatViewModel
class ChatViewModel : ViewModel() {
var adapterMessagesLive: MutableLiveData<AdapterChatItems> = MutableLiveData()
fun addMessage() {
adapterMessagesLive.value = AdapterChatItems(items, addDirection)
}
}
ChatActivity
public class ChatActivity implements LifecycleRegistryOwner {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel = ViewModelProviders.of(this).get(ChatViewModel.class);
viewModel.getAdapterMessagesLive().observe(this, adapterChatItemsObserver -> {
getAdapter().addMessages(adapterChatItemsObserver);
}
});
}
Update
After more debugging, I found out that in Android 7 activity continue receive values from LiveData after onPause
is called. But on older Android SDK its not working.