0

I remember that in kotlin language there is a option to get value by get() property, but can't find how to write it.

What I mean is: I have a LiveData into my ViewModel and I need that access to post in LiveData has only ViewModel and outside just option to get for subscribe.

How I implemented it for now is

class MyViewModel(ctx: Context) : AndroidViewModel(ctx as Application)
{
    private val _showLoadingPB = SingleLiveEvent<Boolean>()

    fun showLoadingPB(): SingleLiveEvent<Boolean>
    {
        return _showLoadingPB
    }
...
}

But I remember that there is an option to write it like this

class MyViewModel(ctx: Context) : AndroidViewModel(ctx as Application)
{
    private val _showLoadingPB = SingleLiveEvent<Boolean>()

    val showLoadingPB: SingleLiveEvent<Boolean>
        get() => _showLoadingPB
}

How to make it works?

1 Answer 1

1

I remembered how it should be

class MyViewModel(ctx: Context) : AndroidViewModel(ctx as Application)
{
    private val _showLoadingPB = SingleLiveEvent<Boolean>()

    val showLoadingPB: LiveData<Boolean>
        get() = _showLoadingPB
}

This way user can't assign new value to your SingleLiveEvent as well as post new event in LiveData, he can just observe it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.