Skip to content

Commit

Permalink
Remove use of org.greenrobot.eventbus
Browse files Browse the repository at this point in the history
  • Loading branch information
atavism committed Jun 20, 2024
1 parent 915e1d4 commit 8b67cb3
Show file tree
Hide file tree
Showing 11 changed files with 105 additions and 64 deletions.
14 changes: 4 additions & 10 deletions android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -384,16 +384,6 @@ dependencies {
// Google Play libraries
implementation 'com.android.billingclient:billing:6.2.0'

// lib that simplifies event bus communication between activities, fragments, threads, services, etc
implementation 'org.greenrobot:eventbus:3.3.1'

// https://mvnrepository.com/artifact/net.jodah/expiringmap
// implementation group: 'net.jodah', name: 'expiringmap', version: '0.5.9'
// implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.7.0'
// implementation group: 'commons-codec', name: 'commons-codec', version: '1.12'
// https://mvnrepository.com/artifact/javax.mail/mail
// implementation group: 'javax.mail', name: 'mail', version: '1.4.7'

implementation 'com.stripe:stripe-android:20.17.0'
annotationProcessor "org.androidannotations:androidannotations:$androidAnnotationsVersion"
implementation("org.androidannotations:androidannotations-api:$androidAnnotationsVersion")
Expand Down Expand Up @@ -423,6 +413,10 @@ dependencies {
testImplementation "io.mockk:mockk:1.13.5"
}

kapt {
correctErrorTypes true
}

apply plugin: 'com.google.gms.google-services'

sentry {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import org.getlantern.mobilesdk.Settings
import org.getlantern.mobilesdk.StartResult
import org.getlantern.mobilesdk.util.DnsDetector
import org.getlantern.mobilesdk.util.LanguageHelper
import org.greenrobot.eventbus.EventBus
import java.io.PrintWriter
import java.io.StringWriter
import java.lang.reflect.InvocationTargetException
Expand Down Expand Up @@ -136,7 +135,7 @@ abstract class SessionManager(application: Application) : Session {
val oldLocale = prefs.getString(LANG, "")
prefs.edit().putString(LANG, locale.toString()).apply()
if (locale.language != oldLocale) {
EventBus.getDefault().post(locale)
//EventBus.getDefault().post(locale)
}
}
}
Expand Down Expand Up @@ -183,7 +182,7 @@ abstract class SessionManager(application: Application) : Session {
}

override fun updateAdSettings(adSettings: AdSettings) {
EventBus.getDefault().post(adSettings)
//EventBus.getDefault().post(adSettings)
}

/**
Expand Down Expand Up @@ -356,7 +355,7 @@ abstract class SessionManager(application: Application) : Session {
val b = Bandwidth(percent, remaining, allowed, ttlSeconds)
Logger.debug("bandwidth", b.toString())
saveLatestBandwidth(b)
EventBus.getDefault().postSticky(b)
//EventBus.getDefault().postSticky(b)
}

fun setSurveyLinkOpened(url: String?) {
Expand Down Expand Up @@ -401,7 +400,7 @@ abstract class SessionManager(application: Application) : Session {
}

val st = Stats(city, country, countryCode, httpsUpgrades, adsBlocked, hasSucceedingProxy)
EventBus.getDefault().postSticky(st)
//EventBus.getDefault().postSticky(st)

// save last location received
prefs.edit().putString(SERVER_COUNTRY, country)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

import org.getlantern.mobilesdk.Logger;
import org.getlantern.mobilesdk.model.Event;
import org.greenrobot.eventbus.EventBus;

import java.net.Inet6Address;
import java.net.InetAddress;
Expand Down Expand Up @@ -114,7 +113,6 @@ private String doGetDnsServer() {
public void publishNetworkAvailability() {
if (findActiveNetwork() == null) {
Logger.debug(TAG, "No network available");
EventBus.getDefault().postSticky(Event.NoNetworkAvailable);
}
}

Expand Down
46 changes: 18 additions & 28 deletions android/app/src/main/kotlin/org/getlantern/lantern/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import io.lantern.model.VpnModel
import kotlinx.coroutines.*
import okhttp3.Response
import org.getlantern.lantern.activity.WebViewActivity_
import org.getlantern.lantern.event.AppEvent
import org.getlantern.lantern.event.EventManager
import org.getlantern.lantern.model.AccountInitializationStatus
import org.getlantern.lantern.model.Bandwidth
Expand All @@ -53,9 +54,6 @@ import org.getlantern.mobilesdk.model.Event
import org.getlantern.mobilesdk.model.LoConf
import org.getlantern.mobilesdk.model.LoConf.Companion.fetch
import org.getlantern.mobilesdk.model.Survey
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.Locale
import java.util.concurrent.*

Expand Down Expand Up @@ -99,7 +97,16 @@ class MainActivity : FlutterActivity(), MethodChannel.MethodCallHandler,
LanternApp.getSession().dnsDetector.publishNetworkAvailability()
}
}

eventManager.subscribeAppEvent { appEvent ->
if (appEvent is AppEvent.StatsEvent) {
val stats = appEvent.stats
Logger.debug("Stats updated", stats.toString())
sessionModel.saveServerInfo(
Vpn.ServerInfo.newBuilder().setCity(stats.city).setCountry(stats.country)
.setCountryCode(stats.countryCode).build(),
)
}
}
MethodChannel(
flutterEngine.dartExecutor.binaryMessenger,
"lantern_method_channel",
Expand Down Expand Up @@ -131,10 +138,6 @@ class MainActivity : FlutterActivity(), MethodChannel.MethodCallHandler,
super.onCreate(savedInstanceState)

Logger.debug(TAG, "Default Locale is %1\$s", Locale.getDefault())
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this)
}
Logger.debug(TAG, "EventBus.register finished at ${System.currentTimeMillis() - start}")

val intent = Intent(this, LanternService_::class.java)
context.startService(intent)
Expand Down Expand Up @@ -198,7 +201,6 @@ class MainActivity : FlutterActivity(), MethodChannel.MethodCallHandler,
vpnModel.destroy()
sessionModel.destroy()
replicaModel.destroy()
EventBus.getDefault().unregister(this)
}

override fun onMethodCall(
Expand All @@ -223,7 +225,7 @@ class MainActivity : FlutterActivity(), MethodChannel.MethodCallHandler,
fetch { loconf -> runOnUiThread { processLoconf(loconf) } }
}

@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
//@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
fun onInitializingAccount(status: AccountInitializationStatus) {
val appName = getString(R.string.app_name)

Expand All @@ -237,20 +239,17 @@ class MainActivity : FlutterActivity(), MethodChannel.MethodCallHandler,
val tvMessage: TextView = dialogView.findViewById(R.id.tvMessage)
tvMessage.text = getString(R.string.init_account, appName)
dialogView.findViewById<View>(R.id.btnCancel).setOnClickListener {
EventBus.getDefault().removeStickyEvent(status)
accountInitDialog?.dismiss()
finish()
}
accountInitDialog?.show()
}

AccountInitializationStatus.Status.SUCCESS -> {
EventBus.getDefault().removeStickyEvent(status)
accountInitDialog?.let { it.dismiss() }
}

AccountInitializationStatus.Status.FAILURE -> {
EventBus.getDefault().removeStickyEvent(status)
accountInitDialog?.let { it.dismiss() }

Utils.showAlertDialog(
Expand All @@ -266,33 +265,24 @@ class MainActivity : FlutterActivity(), MethodChannel.MethodCallHandler,
}
}

@Subscribe(threadMode = ThreadMode.MAIN)
//@Subscribe(threadMode = ThreadMode.MAIN)
fun vpnStateChanged(state: VpnState) {
updateStatus(state.useVpn)
}

@Subscribe(threadMode = ThreadMode.MAIN)
//@Subscribe(threadMode = ThreadMode.MAIN)
fun lanternStarted(status: LanternStatus) {
updateUserData()
updatePaymentMethods()
updateCurrencyList();
}

@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
//@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
fun onEvent(event: Event) {
eventManager.onNewEvent(event = event)
}

@Subscribe(threadMode = ThreadMode.MAIN)
fun statsUpdated(stats: Stats) {
Logger.debug("Stats updated", stats.toString())
sessionModel.saveServerInfo(
Vpn.ServerInfo.newBuilder().setCity(stats.city).setCountry(stats.country)
.setCountryCode(stats.countryCode).build(),
)
}

@Subscribe(threadMode = ThreadMode.MAIN)
//@Subscribe(threadMode = ThreadMode.MAIN)
fun bandwidthUpdated(bandwidth: Bandwidth) {
Logger.debug("bandwidth updated", bandwidth.toString())
vpnModel.updateBandwidth(bandwidth)
Expand Down Expand Up @@ -373,7 +363,7 @@ class MainActivity : FlutterActivity(), MethodChannel.MethodCallHandler,
}


@Subscribe(threadMode = ThreadMode.MAIN)
//@Subscribe(threadMode = ThreadMode.MAIN)
fun processLoconf(loconf: LoConf) {
doProcessLoconf(loconf)
}
Expand Down Expand Up @@ -651,7 +641,7 @@ class MainActivity : FlutterActivity(), MethodChannel.MethodCallHandler,
}

// Recreate the activity when the language changes
@Subscribe(threadMode = ThreadMode.MAIN)
// @Subscribe(threadMode = ThreadMode.MAIN)
fun languageChanged(locale: Locale) {
recreate()
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package org.getlantern.lantern.event

import kotlin.coroutines.coroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.filterIsInstance
import org.getlantern.lantern.model.Bandwidth
import org.getlantern.lantern.model.Stats

object EventBus {
private val _events = MutableSharedFlow<Any>()
val events = _events.asSharedFlow()

suspend fun publish(event: Any) {
_events.emit(event)
}

suspend inline fun <reified T> subscribe(crossinline onEvent: (T) -> Unit) {
events.filterIsInstance<T>()
.collectLatest { event ->
coroutineContext.ensureActive()
onEvent(event)
}
}
}

sealed class AppEvent {
data class StatsEvent(val stats: Stats) : AppEvent()
}

Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,20 @@ package org.getlantern.lantern.event

import android.os.Handler
import android.os.Looper
import androidx.lifecycle.LifecycleOwner
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
import org.getlantern.mobilesdk.model.Event
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import java.util.EnumMap
import java.util.concurrent.ConcurrentSkipListSet
import java.util.concurrent.atomic.AtomicReference
import org.getlantern.mobilesdk.Logger
import org.getlantern.lantern.model.Stats

abstract class EventManager(
private val name: String,
Expand Down Expand Up @@ -52,6 +60,20 @@ abstract class EventManager(
}
}

suspend fun postStatsEvent(stats: Stats) {
CoroutineScope(Dispatchers.IO).launch {
EventBus.publish(AppEvent.StatsEvent(stats))
}
}

fun subscribeAppEvent(onEvent: (AppEvent) -> Unit) {
CoroutineScope(Dispatchers.Main + SupervisorJob()).launch {
EventBus.subscribe<AppEvent> { appEvent ->
onEvent(appEvent)
}
}
}

@Synchronized
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
activeSink.set(events)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import io.lantern.model.Vpn
import org.getlantern.lantern.util.PlansUtil
import org.getlantern.mobilesdk.Logger
import org.getlantern.mobilesdk.model.SessionManager
import org.greenrobot.eventbus.EventBus
import org.joda.time.LocalDateTime
import java.text.SimpleDateFormat
import java.util.Currency
Expand Down Expand Up @@ -336,7 +335,7 @@ class LanternSessionManager(application: Application) : SessionManager(applicati
}

if (user.isProUser) {
EventBus.getDefault().post(UserStatus(user.isActive, user.monthsLeft().toLong()))
//EventBus.getDefault().post(UserStatus(user.isActive, user.monthsLeft().toLong()))
prefs.edit().putInt(PRO_MONTHS_LEFT, user.monthsLeft())
.putInt(PRO_DAYS_LEFT, user.daysLeft())
.apply()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import org.getlantern.lantern.model.Utils
import org.getlantern.lantern.model.VpnState
import org.getlantern.lantern.vpn.LanternVpnService
import org.getlantern.mobilesdk.Logger
import org.greenrobot.eventbus.EventBus


class NotificationReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Expand All @@ -21,7 +19,7 @@ class NotificationReceiver : BroadcastReceiver() {
LanternVpnService::class.java,
)
) {
EventBus.getDefault().post(VpnState(false))
//EventBus.getDefault().post(VpnState(false))
context.startService(
Intent(
context,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import org.getlantern.mobilesdk.Logger
import org.getlantern.mobilesdk.StartResult
import org.getlantern.mobilesdk.model.LoConf
import org.getlantern.mobilesdk.model.LoConfCallback
import org.greenrobot.eventbus.EventBus
import java.util.Random
import java.util.concurrent.atomic.AtomicBoolean

Expand Down Expand Up @@ -104,9 +103,9 @@ open class LanternService : Service(), Runnable {
private fun afterStart() {
if (LanternApp.getSession().userId().toInt() == 0) {
// create a user if no user id is stored
EventBus.getDefault().post(
/*EventBus.getDefault().post(
AccountInitializationStatus(AccountInitializationStatus.Status.PROCESSING),
)
)*/
createUser(0)
}

Expand All @@ -115,12 +114,12 @@ open class LanternService : Service(), Runnable {
autoUpdater.checkForUpdates()
}

EventBus.getDefault().postSticky(LanternStatus(Status.ON))
//EventBus.getDefault().postSticky(LanternStatus(Status.ON))

// fetch latest loconf
LoConf.Companion.fetch(object : LoConfCallback {
override fun onSuccess(loconf: LoConf) {
EventBus.getDefault().post(loconf)
//EventBus.getDefault().post(loconf)
}
})
}
Expand All @@ -147,9 +146,9 @@ open class LanternService : Service(), Runnable {
override fun onFailure(@Nullable throwable: Throwable?, @Nullable error: ProError?) {
if (attempts >= MAX_CREATE_USER_TRIES) {
Logger.error(TAG, "Max. number of tries made to create Pro user")
EventBus.getDefault().postSticky(
/*EventBus.getDefault().postSticky(
AccountInitializationStatus(AccountInitializationStatus.Status.FAILURE),
)
)*/
return
}
attempts++
Expand All @@ -169,10 +168,10 @@ open class LanternService : Service(), Runnable {
if (!referral.isEmpty()) {
LanternApp.getSession().setCode(referral)
}
EventBus.getDefault().postSticky(LanternStatus(Status.ON))
/*EventBus.getDefault().postSticky(LanternStatus(Status.ON))
EventBus.getDefault().postSticky(
AccountInitializationStatus(AccountInitializationStatus.Status.SUCCESS),
)
)*/
}
}

Expand Down
Loading

0 comments on commit 8b67cb3

Please sign in to comment.