您可以按照源代码中显示的配方创建自己的转换Transformations
。FWIW,这个示例应用程序演示了一个自定义filter()
实现:
/***
Copyright (c) 2017 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
Covered in detail in the book _Android's Architecture Components_
https://commonsware.com/AndroidArch
*/
package com.commonsware.android.livedata;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MediatorLiveData;
import android.arch.lifecycle.Observer;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
class LiveTransmogrifiers {
interface Confirmer<T> {
boolean test(T thingy);
}
@MainThread
static <X> LiveData<X> filter(@NonNull LiveData<X> source,
@NonNull final Confirmer<X> confirmer) {
final MediatorLiveData<X> result=new MediatorLiveData<>();
result.addSource(source, new Observer<X>() {
@Override
public void onChanged(@Nullable X x) {
if (confirmer.test(x)) {
result.setValue(x);
}
}
});
return(result);
}
}
否则,没有。LiveData
意味着作为一个轻量级的 RxJava 类似物,它是生命周期感知的。如果你需要很多操作符,最好直接使用 RxJava。