Hello Guys I am working in one project in which i...
# android
m
Hello Guys I am working in one project in which i want to call one api in every 5 seconds with Coroutines to check is there new data is available. I have searched on google and found implementation with ticker channel. I have implemented with that, but the senario is like i want to only get the live update between fragment's onCreateView() and onDestroyView() method. ViewModel Implementation to call api with coroutine:
Copy code
@ObsoleteCoroutinesApi
private var orderCollectingChannel = ticker(
    delayMillis = INTERVAL_ORDER_COLLECTING_UPDATES,
    initialDelayMillis = INITIAL_ORDER_COLLECTING_DELAY,
    context = <http://Dispatchers.IO|Dispatchers.IO>
)

 @ObsoleteCoroutinesApi
    fun getOrderCollectingLiveUpdates() {
        Log.d(TAG, "isOrderCollected : $isOrderCollected")
        viewModelScope.launch {
            Log.d(TAG, "Before While : ")
            while (!isOrderCollected) {
                try {
                    Log.d(TAG, "Inside While : Before Call Receive method")
                    orderCollectingChannel.receive()
                    Log.d(TAG, "Inside While : After Call Receive method")
                    Log.d(TAG, "getOrderCollectingLiveUpdates: ")
                    getOrderInfo()
                } catch (e: Exception) {
                    Log.e(TAG, "Exception ${e.localizedMessage}")
                }
            }
        }
    }

 @ObsoleteCoroutinesApi
    fun cancelOrderCollectingLiveUpdates() {
        Log.d(TAG, "isOrderCollected : $isOrderCollected")
        orderCollectingChannel.cancel()
    }

@ObsoleteCoroutinesApi
    override fun onCleared() {
        super.onCleared()
        cancelOrderCollectingLiveUpdates()
    }
Fragment Implementation :
Copy code
@ObsoleteCoroutinesApi
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        startOrderCollectingLiveUpdates()
        Log.d(TAG, "onCreateView: ")
        return super.onCreateView(inflater, container, savedInstanceState)
    }

@ObsoleteCoroutinesApi
override fun onDestroyView() {
    super.onDestroyView()
    Log.d(TAG, "onDestroyView: ")
    stopOrderCollectingLiveUpdates()
}
When the Fragment is created first time and destroyed again via onBackPress, it is working fine. But the problem is when i again enter in that fragment and from onCreateView() the gettingUpdates() method is called , i am getting the exception ProducerCoroutine was cancelled which leads the app crash. Any one have idea how to solve this problem?