Lightweight library for broadcasting using kotlin coroutine
Download
// add in your dependencies
dependencies {
// kotlin coroutine required
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.8'// add broadcast lib
implementation 'com.utsman.broadcast:broadcast:1.0.1'
}
Usage
Observing data
// single keyBroadcast.with(GlobalScope).observer("your key") { data ->GlobalScope.launch(Dispatchers.Main) {
// data observable here in main scope// update your ui or logic
}
}
// multiple keyBroadcast.with(GlobalScope).observer { key, data ->when (key) {
"key 1"->// data key 1"key 2"->// data key 2
}
}
Post data
Broadcast.with(GlobalScope).post("your key", "your data any type")
Sample Activity
classMainActivity : AppCompatActivity() {
privatevalKEY="message"privatevalKEY2="uhuy"privatevalKEY3="yoi"data classSampleData(
varmessage:String
)
overridefunonCreate(savedInstanceState:Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
observingBroadcast()
val dataMessage ="This message send from broadcast"GlobalScope.launch {
delay(2000)
Broadcast.with(this).post(KEY, dataMessage)
delay(1000)
Broadcast.with(this).post(KEY2, "uhuy data")
// post data classval data =SampleData(message ="message from data class")
delay(1000)
Broadcast.with(this).post(KEY3, data)
}
}
privatefunobservingBroadcast() {
// single keyBroadcast.with(GlobalScope).observer(KEY) { data ->GlobalScope.launch(Dispatchers.Main) {
val message = data asString
tx_log.text = message
}
}
// multiple keyBroadcast.with(GlobalScope).observer { key, data ->when (key) {
KEY2-> {
GlobalScope.launch(Dispatchers.Main) {
val message = data asString
tx_log.text = message
}
}
KEY3-> {
// observing data classGlobalScope.launch(Dispatchers.Main) {
val dataSample = data asSampleData
tx_log.text = dataSample.message
}
}
}
}
}
}
Copyright 2020 Muhammad Utsman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
About
Lightweight library for broadcasting using kotlin coroutine