AltBeacon / android-beacon-library

Allows Android apps to interact with BLE beacons
Apache License 2.0
2.83k stars 836 forks source link

Add Experimental LiveData support for ranging and monitoring #1025

Closed davidgyoung closed 3 years ago

davidgyoung commented 3 years ago

This adds experimental LiveData support for beacon ranging and monitoring. With this change, it is possible to do the following from a Kotlin Activity instead of using RangeNotifier and MonitorNotifier:

    val monitoringObserver = Observer<Int> { state ->
        var stateString = "inside"
        if (state == MonitorNotifier.OUTSIDE) {
            stateString == "outside"
        }
        Log.d(TAG, "monitoring state changed to : $stateString")
    }

    val rangingObserver = Observer<Collection<Beacon>> { beacons ->
        Log.d(TAG, "Ranged: ${beacons.count()} beacons")
    }

        // These two lines set up a Live Data observer so this Activity can get beacon data from the Application class
        val regionViewModel = BeaconManager.getInstanceForApplication(this).getRegionViewModel(region)
        // observer will be called each time the monitored regionState changes (inside vs. outside region)
        regionViewModel.regionState.observe(this, monitoringObserver)
        // observer will be called each time a new list of beacons is ranged (typically ~1 second in the foreground)
        regionViewModel.rangedBeacons.observe(this, rangingObserver)