RxJava过滤器被忽略

时间:2018-08-24 06:41:57

标签: android android-activity fragment rx-java2

在班级Activity中,我创建了一个Fragment。要检测片段是否已准备好,我在片段中有一个布尔标志isInitialized。现在,我想在我的活动中运行一些代码,为此,我必须确保已准备好片段并且isInitialized是真实的。现在,我写了一些RxJava代码来对Activity

中变量的变化做出反应
Observable.just(fragment.isInitialized)
            .filter { _ -> true }
            .subscribe {  load() }

如果我运行我的应用程序,则即使isInitialized为假,也会始终调用方法负载。我的代码有什么问题?

2 个答案:

答案 0 :(得分:1)

假设isInitialized是一个布尔值,您需要根据该值进行过滤。目前,您针对每种情况都返回true。

from __future__ import division
import matplotlib.pyplot as plt
import numpy as np

x = [0,1,2,3,4,5,6,7,8,9,10,11,12]
freq = [0.93, 0.87,0.86,0.87,0.93,0.84,0.74,0.79,0.78,0.95,0.88,0.8, 0.71]

width = 0.1 # width of the bars
xticklabels = ['NR-AHR','NR-AR','NR-AR-LBD','NR-Aromatase','NR-ER','NR-ER-LBD','NR-PPARG','SR-ARE','SR-HSE','SR-MMP','SR-P53','SR-ATAD5','AM']
fig, ax = plt.subplots()
rects1 = ax.bar(x, freq, width, color='b')
#xlabels=['X1', 'X2', 'X3', 'X4', 'X5', 'X6', 'X7', 'X8', 'X9', 'X10', 'X11', 'X12', 'X13']
ax.set_ylim(0.6,1)
ax.set_ylabel('auc-roc', fontsize=13)
#xlabels, rotation=45, rotation_mode="anchor"
ax.set_xticks(np.add(x,(width/2.2))) # set the position of the x ticks
ax.set_xticklabels(xticklabels,rotation = 75, ha="right")
#ax.set_xticklabels(xlabels, rotation=45)
def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/1., 1*height,
                '%.2f' %(height),
                ha='center', va='bottom')

autolabel(rects1)


rects1[0].set_color('r')
rects1[1].set_color('r')
rects1[2].set_color('r')
rects1[3].set_color('r')
rects1[4].set_color('r')
rects1[5].set_color('r')
rects1[6].set_color('r')
rects1[7].set_color('g')
rects1[8].set_color('g')
rects1[9].set_color('g')
rects1[10].set_color('g')
rects1[11].set_color('g')
rects1[12].set_color('b')
#fig = matplotlib.pyplot.gcf()
fig.set_size_inches(3.31, 3.5)
plt.savefig('Figure1.pdf', bbox_inches='tight')
plt.show() 

答案 1 :(得分:1)

如果isInitialized是一个基本字段,则无法对这样的更改做出反应。请改用BehaviorSubject<Boolean>

在您的片段中:

BehaviorSubject<Boolean> isInitialized = BehaviorSubject.create();

初始化代码中的某处:

isInitialized.onNext(true);

在您的加载代码中:

fragment.isInitialized
        .filter { _ -> true }
        .observeOn(Schedulers.io())
        .doOnNext { load() }
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe { /* loaded */ }