How to create masterKey after MasterKeys deprecated in Android

try this one MasterKey masterKey = new MasterKey.Builder(context, MasterKey.DEFAULT_MASTER_KEY_ALIAS) .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) .build(); SharedPreferences sharedPreferences = EncryptedSharedPreferences.create( context, SHARED_PREF_NAME, masterKey, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM);

Android Kotlin Coroutines: what is the difference between flow, callbackFlow, channelFlow,… other flow constructors

For callbackFlow: You cannot use emit() as the simple Flow (because it’s a suspend function) inside a callback. Therefore the callbackFlow offers you a synchronized way to do it with the trySend() option. Example: fun observeData() = flow { myAwesomeInterface.addListener{ result -> emit(result) // NOT ALLOWED } } So, coroutines offer you the option of … Read more

assign variable only if it is null

The shortest way I can think of is indeed using the elvis operator: value = value ?: newValue If you do this often, an alternative is to use a delegated property, which only stores the value if its null: class Once<T> { private var value: T? = null operator fun getValue(thisRef: Any?, property: KProperty<*>): T? … Read more

How to make sealed classes generic in kotlin?

your Object can’t have a generic type in Kotlin but this could be solved simply by following the example below: sealed class ResponseState<out T> { data object Loading : ResponseState<Nothing>() data class Error(val throwable: Throwable) : ResponseState<Nothing>() data class Success<T>(val item: T) : ResponseState<T>() } writing: val _state = MutableLiveData<ResponseState<MessageModel>>() _state.postValue(ResponseState.Loading) myNetworkCall { response, e … Read more

Kotlin – versus

The difference is that a plain <T> means that it can be nullable. (which is represented by Any?). Using <T: Any> will restrict T to non-nullable types. So the difference is that <T> is an implicit <T: Any?>.

How to emit Flow value from different function? Kotlin Coroutines

You can use StateFlow or SharedFlow APIs for such use case. Here’s a sample code with the usage of StateFlow. import kotlinx.coroutines.* import kotlinx.coroutines.flow.* val chatFlow = MutableStateFlow<String>(“”) fun main() = runBlocking { // Observe values val job = launch { chatFlow.collect { print(“$it “) } } // Change values arrayOf(“Hey”, “Hi”, “Hello”).forEach { delay(100) … Read more

When and how to use Result in Kotlin?

TL;DR: never in business code (prefer custom sealed classes), but you can consider Result if you build a framework that must relay all kinds of errors through a different way than the exception mechanism (e.g. kotlinx.coroutines’s implementation). First, there is actually a list of use cases for the motivation of the initial introduction of Result, … Read more