How to combine two live data one after the other?

前端 未结 7 1740
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 05:13

I have next use case: User comes to registration form, enters name, email and password and clicks on register button. After that system needs to check if email is taken or n

相关标签:
7条回答
  • 2020-12-13 05:54

    You can define a method that would combine multiple LiveDatas using a MediatorLiveData, then expose this combined result as a tuple.

    public class CombinedLiveData2<A, B> extends MediatorLiveData<Pair<A, B>> {
        private A a;
        private B b;
    
        public CombinedLiveData2(LiveData<A> ld1, LiveData<B> ld2) {
            setValue(Pair.create(a, b));
    
            addSource(ld1, (a) -> { 
                 if(a != null) {
                    this.a = a;
                 } 
                 setValue(Pair.create(a, b)); 
            });
    
            addSource(ld2, (b) -> { 
                if(b != null) {
                    this.b = b;
                } 
                setValue(Pair.create(a, b));
            });
        }
    }
    

    If you need more values, then you can create a CombinedLiveData3<A,B,C> and expose a Triple<A,B,C> instead of the Pair, etc. Just like in https://stackoverflow.com/a/54292960/2413303 .

    EDIT: hey look, I even made a library for you that does that from 2 arity up to 16: https://github.com/Zhuinden/livedata-combinetuple-kt

    0 讨论(0)
提交回复
热议问题