instacart / truetime-android

Android NTP time library. Get the true current time impervious to device clock time changes
https://tech.instacart.com/truetime/
Apache License 2.0
1.41k stars 194 forks source link

TrueTimeRx initial in Application.onCreate(), where I should add clear() for this disposable? #108

Open thuypt opened 5 years ago

thuypt commented 5 years ago

Regarding example, we got a Disposable at time TrueTimeRx initial in Application.onCreate(), it should be added in a CompositeDisposable like this:

private CompositeDisposable disposables; disposables.add(trueTimeRxDisposable)

Problem is we don't have something like onDestroy in Application layer, so where and when I should call disposables.clear()?

MarkVillacampa commented 5 years ago

You don't need to dispose of it. If you call TrueTimeRx in your Application, it means its lifetime is tried to the lifetime of the application, so you never want to stop observing it. When either a successful time or an error comes through the subscription, the subscription will be closed, so you wont need to stop observing it early.

  For cleanliness, I've added the disposables.clear() call in the onTerminate method which would be the Application equivalent of onDestroy.

CyxouD commented 6 months ago

For cleanliness, I've added the disposables.clear() call in the onTerminate method which would be the Application equivalent of onDestroy.

MarkVillacampa As far as I know, It is not equivalent, because onTerminate isn't always called.

thuypt This is how I handle it with retries:

override fun onCreate() {
        super.onCreate()

        with(ProcessLifecycleOwner.get()) {
            lifecycleScope.launch {
                lifecycle.repeatOnLifecycle(Lifecycle.State.CREATED) {
                    handleTrueTime()
                }
            }
        }
    }

    private fun CoroutineScope.handleTrueTime() = launch {
        var disposable: Disposable? = null
        try {
            while (isActive) {
                disposable?.dispose()
                disposable = TrueTimeRx.build()
                    .initializeNtp(NTP_APPLE)
                    .subscribeOn(Schedulers.io())
                    .subscribe(
                        {
                            // Note that it not always invokes
                            Log.d(
                                TAG,
                                "TrueTime was initialized"
                            )
                        }
                    ) { throwable: Throwable ->
                        // Note that it not always invokes
                        Sentry.captureException(throwable)
                        Log.d(
                            TAG,
                            "TrueTime wasn't initialized: ${throwable}"
                        )
                    }
                delay(DELAY_BETWEEN_CLOCK_RE_SYNC)
            }
        } finally {
            disposable?.dispose()
        }

    }