hadilq/LiveEvent

Add event delivering to the first subscriber even if there was no subscribers before

suhocki opened this issue · 5 comments

This may be an optional feature, but I recommend adding it, as there are several cases where it can be useful.

I had this issue as well. #24 In the end we couldn't come to an agreement about behaviour and the PR was closed. Oh well.

But it got me thinking about the problem and in the end I ended up writing a full stream replacement of LiveEvent that I called SingleLiveEventStream. Rather than being backed by LiveData it's backed by RxJava. It allows for multiple observers with different lifecycle states. (The multiple fragment example Hadi was concerned with.) The stream doesn't start emitting until all lifecycles are in a good state. Finally, it buffers events emitted if there are no observers so it's not possible to step on top of the previous event if the observer hasn't yet processed it.

It's admittedly a "heavier" than LiveEvent and it's very experimental. I'm not sure I'd use it in production. It's just something to think about.

I too have this issue if use setValue before subscribe. In init fun of ViewModel

Thanks you @suhocki, @fergusonm, and @JajaComp for your contribution. And sorry for being late! As @fergusonm mentioned there are some restrictions when you use LiveData, so I came up with another solution based on RxJava or Coroutines. For instance, for RxJava you just need to use startswith operator to solve it, if I understand the problem correctly! That solution also supports saving data which is a step further to be a practical solution. You can find those libraries in https://github.com/hadilq/RxLifecycleHandler/ and https://github.com/hadilq/CoroutineLifecycleHandler/ libraries. The Coroutine library is more update but I can update the RxJava one to catch up with its twin library.

@hadilq This quite a needed feature for the case when the fragment is recreated during fragment navigation in the back stack.
I have logic in ViewModel that gets executed during fragment recreation. In the current implementation all the events that were fired during recreation (before observe()) methods are ignored.

@fergusonm explanation was quite good here. I don't think we need to open this issue again.

Thanks @amatkivskiy for your contribution.