RxJava2成功总是被调用两次

时间:2019-01-16 06:41:06

标签: java android rx-java2 mvp rx-android

我正在使用Retrofit和RxJava2(与RxAndroid)实现MVP架构。我有以下设置

NetworkInterface.java在哪里进行改造

public interface NetworkInterface {
    @GET("/input")
    Single<List<InformationData>> getInfoData();
}

InformationDataDao.java信息数据的数据访问层

@Dao
public interface InformationDataDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    Completable createInfoData(List<InformationData> infoData);
}

MainPresenter.java,其中正在公共类MainPresenter {

    public MainPresenter() {

    }

    // Method called to initialize the subscription
    @Override
    public void subscribe() {
        this.collectInfoData();
    }

    private void collectInfoData() {
        Single<List<InformationData>> singleInfoData = networkInterface.getInfoData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());

        singleInfoData.subscribe(informationDatas -> {
            InformationDataDao informationDataDao = database.informationDataDao();
            informationDataDao.createInfoData(informationDatas);

            // What made me detect that this was being called twice
            Log.d(Constant.LOG_TAG, "Info Data: " + informationDatas.size());

            // Rest of the code here
        }, Throwable::printStackTrace);
    }
}

SplashActivity.java调用演示者的方法

public class SplashActivity extends AppCompatActivity {

    // Helps in getting the location
    private FusedLocationProviderClient locationClient;

    private SplashPresenter mPresenter;

    @Override
    protected void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);
        setContentView(R.layout.activity_splash);

        mPresenter = new SplashPresenter();
    }

    @Override
    protected void onResume() {
        super.onResume();

        // These three lines ensure that you have the appropriate permissions to proceed. In the third line for instance, the user will be navigated out to the settings pane to turn on location.
        // When he/she returns to the activity, the onResume is called so I'm assuming that's the best place to start the presenter
        this.ensureHasPermissions();
        boolean isGoogleServiceAvailable = this.ensureGoogleServiceAvailability();
        boolean isLocationServiceAvailable = this.ensureLocationServiceAvailable();

        if (isLocationServiceAvailable && isGoogleServiceAvailable) {
            locationClient.getLastLocation()
                    .addOnSuccessListener(this, location -> {
                        // Set the closest location and subscribe
                        presenter.setClosestLocation(location);
                        presenter.subscribe();
                    })
                    .addOnFailureListener(this, Throwable::printStackTrace);
        }
    }
}

SplashPresenter.java中,日志被打印两次,表明完整的回调被调用了两次。有什么想法为什么会这样吗?我对RxJava2很陌生,将非常感谢您提供反馈。

谢谢。

0 个答案:

没有答案