Getting a callback in Kotlin in Android-ThrowExceptions

Exception or error:

I am a newbie in Kotlin and want to learn Lambda functions. I have learning Android for months now .
and wanted to integrate both Kotlin and Andriod , so for practicing I am trying to convert Java code to Kotlin. I am facing trouble while getting callbacks. The below code requires a callback which I am not able to achieve.

I haven’t mentioned that ReservoirPutCallback interface is coded in Java and is in a read-only mode

Here is mycode(Java),in which I am facing errors :-

        if(DISK_CACHE_INITIALIZED){
            Reservoir.putAsync(Constants.SCIENTISTS_CACHE_KEY, scientists,
             **new ReservoirPutCallback()** {
                @Override
                public void onSuccess() {
                    //success
                    DISK_CACHE_DIRTY = false;
                }
                @Override
                public void onFailure(Exception e) {
                    Log.e("CAMPOSHA","PUTTING CACHE TO DISK FAILED");
                }
            });
        }
    }

    public static LiveData<List<Scientist>> bindFromDiskCacheAsync(){
        MutableLiveData<List<Scientist>> scientistLiveData=new MutableLiveData<>();
        if(!DISK_CACHE_INITIALIZED){
            return null;
        }
        **Type resultType = new TypeToken<List<Scientist>>() {}.getType()**;
        Reservoir.getAsync(Constants.SCIENTISTS_CACHE_KEY, resultType,
         new ReservoirGetCallback<List<Scientist>>() {
            @Override
            public void onSuccess(List<Scientist> scientists) {
                scientistLiveData.setValue(scientists);
            }
            @Override
            public void onFailure(Exception e) {
                Log.e("CAMPOSHA","ASYNC REFRESH FROM DISK FAILED");
                scientistLiveData.setValue(null);
            }
        });
        return scientistLiveData;
    }
How to solve:

Kotlin supports what you’re trying to do. You’re actually passing a full object as a parameter, not just a callback. If it was a single callback function, you could use a lambda, but this is more like a “callback object”.

For that, we use anonymous objects rather than lambdas/functions. This is true for both java and kotlin.

The first callback will look like:

Reservoir.putAsync(Constants.SCIENTISTS_CACHE_KEY, scientists,
    object : ReservoirPutCallback {

        override fun onSuccess() {
            //success
            DISK_CACHE_DIRTY = false
        }

        override fun onFailure(e: Exception) {
            Log.e("CAMPOSHA","PUTTING CACHE TO DISK FAILED")
        }
    }
)

The second is roughly the same thing.

Leave a Reply

Your email address will not be published. Required fields are marked *